定制阵列适配器
问题描述:
什么,我基本上是试图做的是填充的ListView我用彩色TextViews。我想我必须创建一个自定义ArrayAdapter。适配器将接收我的类ColorElement的一组对象。这里是适配器定制阵列适配器
public class ColoredAdapter extends ArrayAdapter<ColorElement> {
private final Context context;
private final ArrayList<ColorElement> values;
public ColoredAdapter(Context context, ArrayList<ColorElement> values) {
super(context, R.layout.simple_list_item_1);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view.findViewById(R.id.text1);
textView.setText(((ColorElement)values.get(position)).getName());
textView.setTextColor(((ColorElement)values.get(position)).getClr());
return view;
}
}
代码这是代码中,我创建对象的数组,并设置适配器
ArrayList<ColorElement> values = new ArrayList<ColorElement>();
for(int i = 0; i < answerCount; ++i) {
int num = randNumber.nextInt(colorList.size() - 1);
values.add(colorList.get(num));
}
mAnswerList.setAdapter(new ColoredAdapter(this, values));
colorList由设有序对象的另一个列表。我试图随机化它。我没有得到任何错误,但只需在列表中显示不出来和我不知道我做错了什么线索。
答
你无法拥有自己的ArrayAdapter数据工作实例,这实际上是什么让它无法工作。在你的构造函数中,你应该用你的列表调用super,之后所有东西都可以工作。问题是ArrayAdapter正在使用其内部数组来报告元素的数量,这与您的values.length不匹配。
public ColoredAdapter(Context context, ArrayList<ColorElement> values) {
super(context, R.layout.simple_list_item_1, values);
}
在你获取视图,而不是values.get
,叫getItem(position)
。
其中是您的自定义行xml文件。 – 2012-03-10 14:54:51
我没有自定义行xml文件。我今天就开始了android开发,所以请原谅我:P – wirate 2012-03-10 14:56:31
好吧不要担心和最欢迎在android中关注此链接并忽略Imageview http://www.androidhive.info/2012/02/android-custom-listview-with-image-和文本/ – 2012-03-10 14:57:59