KK_07k11A0585
KK_07k11A0585

Reputation: 2403

How to set an image as a Background to a Button using StateListDrawable (dynamically or programmatically or through code)

Here is my code:

public void setHoverEffect(final Button button,int normalImageId, int hoverImageId) {
        if (button != null) 
        {
            StateListDrawable stateListDrawable = new StateListDrawable();
            stateListDrawable.addState(new int[]{ }, getResources().getDrawable(normalImageId));
            stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, getResources().getDrawable(hoverImageId));
            button.setBackgroundDrawable(stateListDrawable);
        }
}

When I use the above code only the normal image is appearing as background and when I press the button it is not showing the hover image.

When I use the selector.xml file as shown below and set it as background it working fine.

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

I want to do this dynamically in order to avoid creating selector xml file for each and every button in my application. I can't figure it out where my code was wrong or where I have to specify extra attributes... :(

Upvotes: 1

Views: 2702

Answers (1)

Vivek Kumar Srivastava
Vivek Kumar Srivastava

Reputation: 2158

@KK you are doing right way with some mistake

see my code

public void selector(Button b,int pressed_image,int normal_image )
    {
        StateListDrawable states = new StateListDrawable();
        states.addState(new int[] { android.R.attr.state_pressed }, getResources().getDrawable(pressed_image));
        states.addState(new int[] {}, getResources().getDrawable(normal_image));
        b.setBackgroundDrawable(states);
    }

you can say this code is same as your code but there are some difference. I have written states.addState(new int[] { android.R.attr.state_pressed }, getResources().getDrawable(pressed_image)); line before states.addState(new int[] {}, getResources().getDrawable(normal_image));

First try this code, I have tested this code 4-5 times and then post here. I really don't know why changing line code working fine.

Upvotes: 6

Related Questions