Change background color of an item in Android ListActivity onListItemClick

Suraj Bajaj picture Suraj Bajaj · Sep 26, 2012 · Viewed 11.8k times · Source

I know it sounds very simple, and there are questions about this. But none of it could solve my problem. So here we go:

I want to change background color of a list item in a ListActivity when user clicks on it, and change it back to original color when user clicks again (i.e. Select/Unselect item sort of look)

I tried using getChildAt, it works perfectly if I have all the items visible in one screen without having to scroll.

Code:

getListView().getChildAt(position).setBackgroundColor(Color.CYAN);

The problem begins when I have more items in the list and user has to scroll through them. Once background for an item is changed, The background color shows up on the newly visible items as I scroll. Also, the getChildAt(position) returns null (and hence a NullPointerException) when clicking again on the item.

Can anyone please help me with a simple code that helps me change background color of a list item?

Thanks in advance!

Answer

heycosmo picture heycosmo · Sep 26, 2012

Sure thing. I would do this in the getView() method of a custom ListAdapter.

MyAdapter extends SimpleAdapter {
    private ArrayList<Integer> coloredItems = new ArrayList<Integer>();

    public MyAdapter(...) {
        super(...);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);

        if (coloredItems.contains(position)) {
            v.setBackgroundColor(Color.CYAN);
        } else {
            v.setBackgroundColor(Color.BLACK); //or whatever was original
        }

        return v;
    }
}

Update coloredItems when a list item is clicked.

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    if (coloredItems.contains(position)) {
        //remove position from coloredItems
        v.setBackgroundColor(Color.BLACK); //or whatever was original
    } else {
        //add position to coloredItems
        v.setBackgroundColor(Color.CYAN);
    }
}