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

wir*_*ate 1 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我正在创建对象数组和设置适配器的代码

 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));
Run Code Online (Sandbox Code Playgroud)

colorList是另一个有序的对象列表.我想把它随机化.我没有得到任何错误,但列表没有出现,我不知道我做错了什么.

dmo*_*mon 5

您无法拥有自己的ArrayAdapter数据实例,这实际上是它无法正常工作的原因.在你的构造函数中,你应该用你的列表调用super,然后一切都会工作.问题是ArrayAdapter正在使用其内部数组来报告元素的数量,这与您的values.length不匹配.

public ColoredAdapter(Context context, ArrayList<ColorElement> values) {
    super(context, R.layout.simple_list_item_1, values);
}
Run Code Online (Sandbox Code Playgroud)

在你的获取视图中,而不是values.get,调用getItem(position).