Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 360
John Baum Avatar asked Aug 22 '13 16:08

John Baum


2 Answers

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.

like image 196
S.D. Avatar answered Oct 19 '22 04:10

S.D.


Step 1 :

first set the row_selector.xml

Step 2 : apply the selector to the items as

android:background="@drawable/row_selector"

Step 3 : Make a selector for the list, list_selector.xml with all the states transparent to get rid of the default states.

Step 4 : apply the selector to the listview as

android:listSelector="@drawable/list_selector"

like image 45
Ritesh Gune Avatar answered Oct 19 '22 06:10

Ritesh Gune