2014-01-21 208 views
5

請問您可以幫我嗎?我需要更改我的列表視圖項目的背景顏色,手動選擇setSelection(int pos)函數,我需要保留新顏色,直到新的setSelection調用。我已經閱讀了一些如何做到這一點的主題,但我仍然沒有成功。謝謝!Android ListView。如何更改手動選擇項目的背景顏色

+0

嘗試使用'listSelector'爲[這裏](http://stackoverflow.com/q/2183447/1051783) – gunar

+0

檢查這個答案:http://stackoverflow.com/questions/19953285/android -listview-item-background-change – Hulk

+0

是否通過點擊選擇了您的項目?如果是這樣,你可以在listView中使用onItemClick –

回答

8

我已經設法通過使幾個選擇的不同狀態

首先把這個在您的列表視圖

android:listSelector="@drawable/list_selector" 

然後在繪製創建XML文件來控制diferent狀態來實現這一目標

@ drawable/list_selector

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:drawable="@drawable/list_item_bg_normal" android:state_activated="false"/> 
<item android:drawable="@drawable/list_item_bg_pressed" android:state_pressed="true"/> 
<item android:drawable="@drawable/list_item_bg_pressed" android:state_activated="true"/> 
</selector> 

@繪製/ list_item_bg_normal

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="rectangle"> 
<gradient 
    android:startColor="@color/list_background" 
    android:endColor="@color/list_background" 
    android:angle="90" /> 
</shape> 

@繪製/ list_item_bg_pressed

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle"> 
    <gradient 
     android:startColor="@color/list_background_pressed" 
     android:endColor="@color/list_background_pressed" 
     android:angle="90" /> 
</shape> 

在你的ListView選擇

listView.setOnItemClickListener(new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) { 
      view.setSelected(true); 
      ... 
     } 
    } 

不要忘記添加list_background_pressedlist_background添加到您的值/ color.xml中,或者只在每個文件中手動設置顏色。

而且我相信當你使用setSelection(int pos)時,它會自動使用你設置的佈局選擇。

希望它有幫助。

+0

謝謝!我做了你說的,但仍然沒有成功(( –

+0

我編輯了我的代碼與setOnItemClickListener方法,給它一個檢查。 –

+0

謝謝!我會嘗試!糾正我,如果我錯了:函數setSelection自動調用onItemClick我的列表視圖的方法? –

0
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
     if (updateview != null) updateview.setBackgroundColor(Color.TRANSPARENT); 
     updateview = view; 
     view.setBackgroundColor(Color.CYAN); 
    } 
}); 
+0

什麼是updateview? – xRobot

相關問題