1

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... :(

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
KK_07k11A0585
  • 2,381
  • 3
  • 26
  • 33

1 Answers1

6

@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.

Vivek Kumar Srivastava
  • 2,158
  • 1
  • 16
  • 23
  • The order is different. View would match the first drawable state which fit current view'state – jerry May 16 '14 at 15:22