user2966445 user2966445 - 2 months ago 12
Android Question

How to Change DrawableLeft in Android Selector?

How can I change the DrawableLeft image of a button using selectors?

I'm using the below selector file and a shape XML for drawable. When the button is clicked, the image doesn't change.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@drawable/toolbar_button_pressed" android:drawableLeft="@drawable/ic_selected" />
<item android:state_pressed="true" android:drawable="@drawable/toolbar_button_pressed" android:drawableLeft="@mipmap/ic_selected" />
<item android:drawable="@drawable/toolbar_button_normal"></item>
</selector>


toolbar_button_pressed

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
android:radius="10dp"
/>
<solid
android:color="@color/primary_dark"
/>
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp"
/>

<stroke
android:width="1dp"
android:color="@color/divider"
/>
</shape>


Layout Button

<Button
android:id="@+id/background_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btn_background"
android:drawableLeft="@drawable/ic_background"
style="@style/ToolbarButton"
android:drawablePadding="10dp"
android:singleLine="true"
android:layout_weight="1" />

Answer

I was able to solve this using selectors:

        <Button
            android:id="@+id/style_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/style_button_text"
            android:drawableLeft="@drawable/toolbar_drawable_left"
            style="@style/ToolbarButton"
            android:layout_weight="1" />

/res/drawable/toolbar_drawable_left.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_selected="true" android:drawable="@drawable/ic_about_highlight"/>
  <item android:state_pressed="true" android:drawable="@drawable/ic_about_highlight"/>
  <item android:drawable="@drawable/ic_about"></item>
</selector>
Comments