String[] values = new String[] { "Apple", "Banana", "Cola", "Dove", "Elephant", "Fan", "Grapes", "Horse" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>((this, R.layout.row,R.id.textview1, values);
list.setAdapter(adapter);
(包含上述代码的类扩展了ListActivity)我想为不同的行提供不同的背景颜色(例如:textview1的背景颜色应在位置0为绿色,在位置6为红色,在位置7为蓝色)据说我需要使用自定义适配器,但是我不知道如何使用自定义适配器将Apple,Banana,Cola等这些特定值设置为textview1。我的xml文件row.xml如下所示
<TextView
android:layout_width="500dp"
android:layout_height="50dp"
android:text="New Text"
android:layout_alignParentTop="true"
android:id="@+id/ListItem"
android:background="@color/color3"
android:gravity="center|left"
android:paddingLeft="5dp"
android:textSize="20dp"
android:textColor="@color/color1" />
我不知道如何实现自定义适配器。谁能帮助我TextView
使用自定义适配器将这些值设置为,并将不同的背景色设置为TextView
?
首先为row.xml中的TextView提供一个ID(比如说rowText)
您需要创建一个将自身绑定到ListView的适配器。适配器通常如下所示:
public class CustomListAdapter extends BaseAdapter {
String[] values = new String[] { "Apple", "Banana", "Cola", "Dove", "Elephant", "Fan", "Grapes", "Horse" };
public ThumbnailAdapter(MainActivity m) {
thumbnails = thumbs;
mInflater = LayoutInflater.from(m);
}
@Override
public int getCount() {
return values.length;
}
@Override
public Object getItem(int position) {
return values[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.rowText = (TextView) convertView
.findViewById(R.id.rowText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//Set the text here!
holder.rowText.setText(values[position]);
//Set the color here!
holder.rowText.setBackgroundResource(R.color.green);
return convertView;
}
static class ViewHolder {
TextView rowText;
}
}
这只是您的开始。要更改颜色,您可以设置颜色数组并从位置中进行选择。希望能帮助到你!(我还没有测试过代码,但是大多数情况下应该是正确的)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句