Tuesday, June 2, 2015

Android selector important fact

Note: Remember that Android applies the first item in the state list that matches the current state of the object. So, if the first item in the list contains none of the state attributes above, then it is applied every time, which is why your default value should always be last.



The following snippet will never show the checked state because when the system compares the state against the first item, it always matches as there is no specific state of it.



<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:enterFadeDuration="@android:integer/config_shortAnimTime">


    <item>
        <bitmap android:src="@android:drawable/ic_input_add" />
    </item>


    <item android:state_checked="true">
        <bitmap android:src="@android:drawable/star_big_on" />
    </item>


</selector>

Change the order of items and it works.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:enterFadeDuration="@android:integer/config_shortAnimTime"
    >


    <item android:state_checked="true">
        <bitmap android:src="@android:drawable/star_big_on"/>
    </item>

    <item>
        <bitmap android:src="@android:drawable/ic_input_add"/>
    </item>



</selector>

No comments:

Post a Comment