我有一个带有一堆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?
}
});
答案 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
,但我认为这是不可取的,也很难实现。