0

I have defined a ImageButton as being drawn by a selector (which uses several images for different states). I need to change the way the buttons look during runtime.

I know I can use "setBackgroundResource" - but I have made the actual background resource a selector. I need to set the images for the specific states I have used in the selector.

So do I need to somehow obtain the selector, then set the images there? If I just call "setBackgroundResource" I assume this will negate the whole selector.

How do I go about doing this?

Brad
  • 11,262
  • 8
  • 55
  • 74
  • possible duplicate of [replace selector images programmatically](http://stackoverflow.com/questions/4697528/replace-selector-images-programmatically) – Brad Oct 21 '11 at 20:43

2 Answers2

1

I wound up simply replacing the selector when the button changes states as follows. Was fairly simple in the end. Inside the button's class:

    StateListDrawable states = new StateListDrawable();
    states.addState(new int[] {-android.R.attr.state_pressed},getResources().getDrawable(R.drawable.button_normal));
    states.addState(new int[] {android.R.attr.state_pressed},getResources().getDrawable(R.drawable.button_pressed));

    this.setImageDrawable(states);
    this.invalidate();
Brad
  • 11,262
  • 8
  • 55
  • 74
0

You can get the StateListDrawable you set, probably casting the Drawable returned by getDrawable() or getBackground() and then invoke selectDrawable().

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134