0

How to change the states of buttons from the code. I cannot use xml files since I am getting the images from the server.

Using :

Drawable d = new BitmapDrawable(getResources(),bitmap);

I have got the drawable but how do I assign different states and then attach corresponding images for the button?

dejavu
  • 91
  • 6

1 Answers1

1

In xml, we use <selector> element to do so. In code, we use StateListDrawable :

StateListDrawable content = new StateListDrawable();
Drawable pressedDrawable = new BitmapDrawable(getResources(),bitmap);
//Your other drawables (focused, .....)

content.addState(new int[] { android.R.attr.state_pressed }, pressedDrawable);
//Add the other drawables the same way

Button button = (Button) view.findViewById(R.id.my_button);
button.setBackground(content);
iTurki
  • 16,292
  • 20
  • 87
  • 132