2

我有一个带有一堆 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?
    }
});
4

1 回答 1

1

您可以在ListView. 你所要做的就是使用setBackgroundResourceView要返回的。让我给你一个简单的例子:

// 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您在文件夹内创建一个名为的 XML 文件res/drawable

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

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

我知道这似乎很乱,但这是 Android 的方式。您也可以尝试修改View内部setOnItemClickListener,但我认为这是不可取的并且难以实施。

于 2010-09-27T16:46:24.103 回答