android中ListView獲得焦點的項預設是黃色的(模擬器上) 現在因為需求想要自己定義被選中項的背景能實現嗎?
最佳答案
完全可以實現,這用到了Android的Selector(根據組件的狀態顯示該狀態對應的圖片,並以此圖片作為背景顯示)。 把下面的XML檔案儲存成你自己命名的.xml檔案(比如list_bg.xml),注意,這個檔案相當於一個背景圖片選取器,在系統使用時根據ListView中的清單項目的狀態來使用相應的背景圖片,什麼情況使用什麼圖片我在下面都進行了說明。還有,你可以把它看成是一個圖片來使用,放於drawable目錄下,配置背景屬性android:background="@drawable/list_bg"就能達到你需要的目的了。
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:drawable="@drawable/沒有焦點時圖片背景" />
<item android:state_focused="true" android:state_pressed="true" <!--雙條件-->
android:drawable="@drawable/非觸摸模式下獲得焦點並單擊時的背景圖片" />
<item android:state_focused="false" android:state_pressed="true"
android:drawable="@drawable/觸摸模式下單擊時的背景圖片" />
<item android:state_selected="true" android:drawable="@drawable/選中時的圖片背景" />
<item android:state_focused="true" android:drawable="@drawable/獲得焦點時的圖片背景" />
<item android:drawable="@drawable/silver" /> <!--default color -->
</selector>
---------------------------------------------------------------------------------------------------------------
在values下建立一個color.xml<?xml version="1.0" encoding="utf-8"?>
<resources>
<drawable name="darkgray">#808080FF</drawable>
<drawable name="white">#FFFFFFFF</drawable>
<drawable name="silver">#00ffffff</drawable> <!-- 透明色 -->
</resources>
-------------------------------------------------------------------------------------------------------------------------------------------------
main布局檔案中的系統 ListView 控制項,注意這不是 ListViewItem 控制項。
<ListView android:id="@id/android:list" android:layout_width="fill_parent"
android:layout_height="400dip" android:drawSelectorOnTop="false"
android:listSelector="@drawable/list_selector_color"/>
<TextView android:id="@id/android:empty"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Can not find the file!" />
-------------------------------------------------------------------------------------------------------------------
你可以看下原始碼ListView清單項目背景的預設實現 :
SDK目錄\platforms\android-xx\data\res\drawable\list_selector_background.xml