Saturday, November 1, 2014

ListView: press state selector

In this tutorial we will add visual indication to ListView pressed state.

























Step 1: In res/drawable folder create a new file "selector_item_gradient.xml"



<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"            android:drawable="@drawable/gradient_pressed"/>
    <item android:state_focused="true"
            android:drawable="@drawable/gradient_focused"/>
    <item android:state_selected="true"
            android:drawable="@drawable/gradient_selected"/>
    <item android:drawable="@drawable/gradient_normal"/>
</selector>




Step 2: In res/drawable create file "gradient_normal.xml" that is gray.


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <gradient
            android:startColor="#fffdfdfe"
            android:centerColor="#ffe7e7e8"
            android:endColor="#ffb1afa9"
            android:angle="270"/>
</shape>

Step 3: in res/drawable create file "gradient_pressed.xml" that is orange or yellow.


<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <gradient
            android:startColor="#fffdfdfe"
            android:centerColor="#ffe7e7e8"
            android:endColor="#ffb1afa9"
            android:angle="270"/>
</shape> 

Step 4: In the root element of your ITEM list_item_book.xml add following



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:drawSelectorOnTop="false"
              android:background="@drawable/selector_item_gradient"