Question

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?
    }
});
Was it helpful?

Solution

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">
    <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">
    <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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top