1

I want to create a drawable resource to change the image used in an image button when it is disabled.

I have created a drawable resource

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <bitmap android:src="@drawable/enabled_image" />
    </item>
    <item android:state_enabled="false">
        <bitmap android:src="@drawable/disabled_image" />
    </item>
</selector>

And then I am referencing it in the android:src="@drawable/resource". When I call ImageButton.setEnabled(false) the button is not clickable but the style doesn't change.

android:background is used for other stuff (radius colours etc)

LonsomeHell
  • 573
  • 1
  • 7
  • 29

2 Answers2

3

Try this

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/disabled_backgroungd"/>
    <item android:state_pressed="false"
        android:drawable="@drawable/normal_backgroungd" />
    <item android:state_pressed="true"
        android:drawable="@drawable/backgroungd_selected" />
    <item android:state_enabled="true" android:drawable="@drawable/normal_backgroungd"/> 
</selector>

EDIT : State List

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:constantSize=["true" | "false"]
    android:dither=["true" | "false"]
    android:variablePadding=["true" | "false"] >
    <item
        android:drawable="@[package:]drawable/drawable_resource"
        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_hovered=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
        android:state_activated=["true" | "false"]
        android:state_window_focused=["true" | "false"] />
</selector>

EDIT:

The order of the items states in the drawable makes a difference.

LonsomeHell
  • 573
  • 1
  • 7
  • 29
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
  • 1
    The solution works fine. I also found out that the order of the states makes a difference. Can you provide a break down for the order or a link to make sure the cause of the problem is clear. – LonsomeHell Mar 26 '18 at 13:11
0
if(!ImageButton.isEnabled())
{
     //set the drawable         
}