ListView中的Item選中時改變其背景圖檔,如下圖
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiclRnblN0LclHdpZXYyd2LcBzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX9c2RiZGZtJGcoJjWxY0RiZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39DMxUTN1ITM0EDOyIDM1EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
實作原理其實很簡單,如下所示
<ListView
android:id="@+id/lv_jiemu"
android:layout_width="370px"
android:layout_height="wrap_content"
android:listSelector="@drawable/listview_selected" >
</ListView>
ListView有一個listSelector屬性,其大概意思是listview中的item選中時
然後在定義listview_selected.xml檔案,如下所示(此處我是從别人摘抄的)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 沒有焦點時的背景圖檔 -->
<!-- <item android:state_window_focused="false"/> -->
<!-- 非觸摸模式下獲得焦點并單擊時的背景圖檔 -->
<item android:drawable="@drawable/sfd" android:state_focused="true" android:state_pressed="true"/>
<!-- 觸摸模式下單擊時的背景圖檔 -->
<!--
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="@drawable/pic3"/>
-->
<!-- 選中時的圖檔背景 -->
<item android:drawable="@drawable/sfd" android:state_selected="true"/>
<!-- 獲得焦點時的圖檔背景 -->
<item android:drawable="@drawable/sfd" android:state_focused="true"/>
</selector>
然後再運作你的項目,你會發現有意想不到的效果~ 祝大家新年快樂,工作順利,全家幸福~