您可以在您的ListView
的適配器中設置它。你要做的就是使用你要返回的View
上的setBackgroundResource
。讓我給你一個簡單的例子:
// 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選擇。別擔心,這比聽起來容易。你res/drawable
文件夾中創建名爲the_custom_background.xml
的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
另一個叫繪製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>
我知道似乎很雜亂,但這是Android的方式。您也可以嘗試修改setOnItemClickListener
中的View
,但我認爲這是不理想的,也很難實現。
通過實現這種方式,不會背景總是'R.drawable.the_custom_background'?當ListItem被點擊時,我只希望它是'R.drawable.the_custom_background'。我不確定這是什麼邏輯,我認爲它會在setOnItemClickListener裏面... – 2010-09-27 18:55:03
OK ...在這種情況下,請嘗試'v.setBackgroundResource(R.drawable.the_custom_background);''onItemClick'方法內部。 – Cristian 2010-09-27 19:07:02
這是有效的。但是,當用戶點擊另一個listitem時,我希望舊的listitem恢復爲默認的背景色 – 2010-09-27 19:46:42