拥有自定义背景和默认选择器效果(按下/选择时的另一个drawalbe)有点困难,经过几次尝试,我做到了。
您应该在单独的 xml 文件中定义两个选择器:listitem_background.xml
和listitem_selector.xml
.
第一个用于列表项的背景,它会在项目被按下并处于正常状态时产生效果。
第二个用于列表的选择器,它将通过将所有状态设置为 来摆脱列表视图的默认选择器transparent
。
默认选择器效果在第一个 xml 文件中定义:listitem_background.xml。
首先,您需要一个 xml 文件来定义一些可绘制颜色:color_drawable.xml
,在res/values
目录中:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- The color of the normal state. -->
<drawable name="listitem_normal">#E671B8</drawable>
<!-- The two color below show when the item is pressed, you should change that to the color you want. -->
<drawable name="listitem_pressed">#e7eeab</drawable>
<drawable name="listitem_selected">#e7eeab</drawable>
</resources>
然后,listitem_background.xml
在res/drawable
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/listitem_pressed" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="@drawable/listitem_selected" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="@drawable/listitem_selected" android:state_enabled="true" android:state_selected="true"/>
<item android:drawable="@drawable/listitem_normal"/>
</selector>
并且,listitem_selector.xml
在res/drawable
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/android:transparent" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="@color/android:transparent" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="@color/android:transparent"/>
</selector>
将 listitem_background 设置为 listitem:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/listitem_background" >
...
</RelativeLayout>
将 listitem_selector 设置为 listview:
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:listSelector="@drawable/listitem_selector" />