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