Search code examples
androidlistviewandroid-arrayadapter

custom array adapter for android listview


What I'm essentially trying to do is to populate my ListView with colored TextViews. I figured I had to create a custom ArrayAdapter. The adapter will take an array of objects of my class ColorElement. Here is the code for the adapter

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;
    }
}

And this is the code where I'm creating the array of objects and setting the adapter

 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 is another list of objects which is ordered. I'm trying to randomize it. I don't get any errors but the list just doesn't show up and I have no clue about what I'm doing wrong.


Solution

  • You cant have your own instance of the data for the ArrayAdapter to work, that's actually what makes it not work. In your constructor, you should call the super with your list, after that everything will work. The problem is that the ArrayAdapter is using its internal array to report the number of elements, which doesn't match your values.length.

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

    In your get view, instead of values.get, call getItem(position).