2010-09-27 56 views
2

我有一堆ListItem的ListView。當用戶選擇一個項目時,我想將該ListItem的背景更改爲圖像。我怎樣才能做到這一點?如何在選擇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

您可以在您的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,但我認爲這是不理想的,也很難實現。

+0

通過實現這種方式,不會背景總是'R.drawable.the_custom_background'?當ListItem被點擊時,我只希望它是'R.drawable.the_custom_background'。我不確定這是什麼邏輯,我認爲它會在setOnItemClickListener裏面... – 2010-09-27 18:55:03

+0

OK ...在這種情況下,請嘗試'v.setBackgroundResource(R.drawable.the_custom_background);''onItemClick'方法內部。 – Cristian 2010-09-27 19:07:02

+0

這是有效的。但是,當用戶點擊另一個listitem時,我希望舊的listitem恢復爲默認的背景色 – 2010-09-27 19:46:42