如何在选择ListItem时修改它的背景?

时间:2010-09-27 16:20:47

标签: java android listview listviewitem

我有一个带有一堆ListItem的ListView。当用户选择一个项目时,我想将该ListItem的背景更改为图像。我怎么能做到这一点?

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 个答案:

答案 0 :(得分:1)

您可以在ListView的适配器中进行设置。您要做的是使用您要返回的setBackgroundResource上的View。让我举个简短的例子:

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

请注意,我正在使用R.drawable.the_custom_background,这意味着您必须编写一个小的XML选择器。别担心,它比听起来容易。您在the_custom_background.xml文件夹中创建名为res/drawable的XML文件:

<?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>

再次注意,我正在使用@drawable/the_background_color,所以最后在名为res/drawable的{​​{1}}文件夹中创建另一个drawable:

the_background_color

我知道它似乎非常混乱,但这是Android的方式。您也可以尝试修改<?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#FF0000" /> </shape> 中的View,但我认为这是不可取的,也很难实现。