用于android listview的自定义数组适配器

时间:2012-03-10 14:48:18

标签: android listview android-arrayadapter

我实际上要做的是使用彩色TextView填充ListView。我想我必须创建一个自定义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是另一个有序的对象列表。我想把它随机化。我没有得到任何错误,但列表没有出现,我不知道我做错了什么。

1 个答案:

答案 0 :(得分:5)

您无法拥有自己的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)

相关问题