Android transparent selector drawable doesn’t work

May 2015

Today I’ve tried to make selector for my listview. When user selects item it should display arrow right of label. list_highlight Okay. Label is a TextView with drawableRight. And drawableRight links to next selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:enterFadeDuration="@android:integer/config_shortAnimTime"
    android:exitFadeDuration="@android:integer/config_shortAnimTime"
    >

    <item android:drawable="@android:drawable/ic_media_play" android:state_selected="true" />
    <item android:drawable="@android:drawable/ic_media_play" android:state_checked="true" />
    <item android:drawable="@android:color/transparent" />
</selector>

But that code doesn’t work. And here’s the reason why. Initially we doesn’t show an arrow – just transparent color. Color has zero size (0 dp x 0 dp) so when ListView changes state of my CheckedTextView, CheckedTextView changes rightDrawable, but it doesn’t change this size. So solutions is to set max size initially. Blessing, we can point Android framework to do it automatically by adding android:constantSize=”true”. So the final code is:

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

    <item android:drawable="@android:drawable/ic_media_play" android:state_selected="true" />
    <item android:drawable="@android:drawable/ic_media_play" android:state_checked="true" />
    <item android:drawable="@android:color/transparent" />
</selector>

That’s all!

Leave a Reply

Your email address will not be published. Required fields are marked *