Skip to content Skip to sidebar Skip to footer

Android Listview With Different Colors

I am having a little problem using different colors in a ListView. I have tried several things but nothing seems to work private class GameRowAdapter extends ArrayAdapter {

Solution 1:

You are only defining the color in the creation of the view. However for the recycled views you need to set the color again explicitly. There is no guarantee that 6 and 7 will be new views. So always set the color of the view with each call of getView

Solution 2:

Edit: After running a small local test, I think the issue may be that the TextViews you have in each row are in front of the ListView row view. Try setting the model.entry and model.score background colors. /Edit

I think it's coming from the convertViews being reused. Try moving this:

if (position == 6 || position == 7) {
    row.setBackgroundColor(R.color.black);
}

Outside of the if (row == null) block, and change it to this:

if (position == 6 || position == 7) {
    model.entry.setBackgroundColor(R.color.black);
    model.score.setBackgroundColor(R.color.black);

} else {
    model.entry.setBackgroundColor(/*Whatever your default background color is*/);
    model.score.setBackgroundColor(/*Whatever your default background color is*/);
}

So your full getView method would be:

 @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        RowModelViews model;
        if (row == null) {
            LayoutInflater inflater = LayoutInflater.from(GamePlayerActivity.this);
            row = inflater.inflate(R.layout.game_line_layout, null);
            model = new RowModelViews(row);
            model.entry = (TextView) row.findViewById(R.id.gameLineEntry);
            model.score = (TextView) row.findViewById(R.id.gameLineEntryScore);
            row.setTag(model);
        } else {
            model = (RowModelViews) row.getTag();
        }

        if (position == 6 || position == 7) {
            model.entry.setBackgroundColor(R.color.black);
            model.score.setBackgroundColor(R.color.black);
        } else {
            model.entry.setBackgroundColor(/*Whatever your default background color is*/);
            model.score.setBackgroundColor(/*Whatever your default background color is*/);
        }

        model.entry.setText(objects.get(position).entry);
        model.score.setText(objects.get(position).score);

        return row;
    }

Post a Comment for "Android Listview With Different Colors"