mercredi 27 mai 2015

Create custom selector

I've got 3 TextView, and I want to create a custom selector drawable which:

  • creates a rectangular border with round corners (done)
  • gets selected when the user presses one of them

The TextViews:

<LinearLayout android:id="@+id/info" android:layout_marginTop="68dp"
        android:layout_width="wrap_content" android:layout_height="fill_parent"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal">
        <TextView android:id="@+id/tour1"
            android:paddingLeft="10dp" android:paddingRight="10dp"
            android:paddingTop="8dp" android:paddingBottom="8dp"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:background="@drawable/back"
            android:gravity="center"
            android:text="Tour \n disponibili  \n 21"/>

        <TextView android:id="@+id/tour2" android:layout_toRightOf="@+id/tour1"
            android:paddingLeft="10dp" android:paddingRight="10dp"
            android:paddingTop="8dp" android:paddingBottom="8dp"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:background="@drawable/back"
            android:gravity="center"
            android:text="Tour \n prenotabili  \n 16"
            android:layout_marginLeft="16dp"/>

        <TextView android:id="@+id/tour3" android:layout_toRightOf="@+id/tour2"
            android:paddingLeft="10dp" android:paddingRight="10dp"
            android:paddingTop="8dp" android:paddingBottom="8dp"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:background="@drawable/back"
            android:gravity="center"
            android:text="Tour \n preferiti  \n 3"
            android:layout_marginLeft="16dp"/>
</LinearLayout>

My Drawable selector file, back.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://ift.tt/nIICcg">
    <item>
        <shape android:shape="rectangle" >

        <stroke android:width="1dip"
            android:color="#4fa5d5"/>
        <corners android:radius="7dp"/>
    </shape>
</item>
<item  android:state_pressed="true">
    <shape android:shape="rectangle" >
        <stroke android:width="5dip"
            android:color="#ff0000"/>
        <corners android:radius="7dip" />
    </shape>
</item>

I would like to know how:

  • to successfully apply the attribute "?android:attr/selectableItemBackground"
  • or, as I just tried to do, to apply a custom one.

Unfortunately, I wasn't able to implement any of the above. In my example, the TextViews always show the first item (the one without the android:state_pressed="true" attribute) selected and when I press them they never switch to the item with the android:state_pressed="true" attribute.

Where are the flaws in my code?

Aucun commentaire:

Enregistrer un commentaire