views:

52

answers:

1

I have a ListView with a bunch of ListItem's. When the user selects an item, I would like to change that ListItem's background to an image. How can I accomplish this?

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> a, View v, int position, long id) {
    // how do I change the ListItem background here?
    }
});
+1  A: 

You can set that in the adapter of your ListView. What you have to do is use the setBackgroundResource on the View that you are returning. Let me give you a brief example:

// lets suppose this is your adapter (which obviously has
//to be a custom one which extends from on of the main
//adapters BaseAdapter, CursorAdapter, ArrayAdapter, etc.)

// every adapter has a getView method that you will have to overwrite
// I guess you know what I'm talking about
public View getView( args blah blah ){
    View theView;
    // do stuff with the view

    // before returning, set the background
    theView.setBackgroundResource(R.drawable.the_custom_background);

    return theView;
}

Notice that I'm using R.drawable.the_custom_background, which means that you have to write a little XML selector. Don't worry, it's easier than it sounds. You create an XML file called the_custom_background.xml inside the res/drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    <item 
        android:state_pressed="true" 
        android:state_enabled="true"
        android:drawable="@drawable/the_background_color" />
</selector>

Notice again, I'm using @drawable/the_background_color, so finally create another drawable in the res/drawable folder called the_background_color:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    <solid android:color="#FF0000" />
</shape>

I know it seems to be very messy, but this is the Android way. You could also try to modify the View inside the setOnItemClickListener, but I think that's undesirable and harder to implement.

Cristian
By implementing this way, won't the background ALWAYS be `R.drawable.the_custom_background` ? I only want it to be `R.drawable.the_custom_background` when the ListItem is clicked. I'm not sure where that logic is, I assumed it would be inside of setOnItemClickListener...
Sheehan Alam
OK... in that case, try `v.setBackgroundResource(R.drawable.the_custom_background);` inside the `onItemClick` method.
Cristian
That works. But when the user clicks another listitem, I want the old listitem to revert back to the default background color
Sheehan Alam
I have awarded you the answer, since I can change the background color. I have opened a new question regarding only changing the background color of the selected item: http://stackoverflow.com/questions/3808175/listview-selector-problem-selection-does-not-expire
Sheehan Alam