Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

android - Custom selector for list background

I am trying to set some custom selector states to every item in my listview. I have tried the following"

list_selector.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"
          android:drawable="@drawable/row_selected_background" />
    <item android:state_activated="true"
          android:drawable="@drawable/row_selected_background" />
    <item android:state_focused="true"
          android:drawable="@drawable/row_selected_background" />
    <item android:drawable="@drawable/row_background" />
</selector>

list.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <ListView
            android:id="@android:id/list"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/row_background"
            android:listSelector="@drawable/list_selector">

    </ListView>
</RelativeLayout>

For some reason, the list unselected background color is as it is defined. But the on pressed/click is always the default android holo blue for a list. What am i doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use android:state_pressed to specify pressed states.


Drawable to use: /res/drawable/bg.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <solid android:color="@android:color/holo_red_dark"/>
</shape>

Selector to use: /res/drawable/item.xml

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

ListView:

    <ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:saveEnabled="true"
    android:listSelector="@drawable/item"
    />

Result on pressing a list item:

enter image description here

Note: List selector is drawn behind Item View, Item View may have its own background.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...