カスタムの背景とデフォルトのセレクター効果 (押された/選択されたときに別の drawalbe) を持つのは少し難しいですが、数回試行した後、作成しました。
別々の xml ファイルで 2 つのセレクターを定義する必要があります:listitem_background.xml
とlistitem_selector.xml
.
最初のものはリスト項目の背景に使用され、項目が押されて通常の状態にあるときに効果を発揮します。
2 つ目はリストのセレクターに使用され、すべての状態を に設定することで、リスト ビューのデフォルトのセレクターを取り除きますtransparent
。
デフォルトのセレクター効果は、最初の xml ファイル listitem_background.xml で定義されています。
color_drawable.xml
まず、いくつかの描画可能な色を定義するための 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
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:listSelector="@drawable/listitem_selector" />