12

I am trying to set an image on the right side of my button after the button has been clicked. I want to do this via code.

I have seen how to change the background resource via code but I am not able to find any examples showing how to change the sides via code. Is it possible?

  • what do you mean by side change?, was your image on the left side of button before the button click? – Yashwanth Kumar Sep 11 '11 at 19:19
  • It's on the right side and it's a red dot. I want to change it green on click. (It's a toggle button) –  Sep 11 '11 at 19:26
  • 4
    setCompoundDrawablesWithIntrinsicBounds related question: http://stackoverflow.com/questions/4250923/how-to-change-a-buttons-icon-programmatically – Erdal Sep 11 '11 at 19:43

2 Answers2

28

You need to use the

public void setCompoundDrawables (Drawable left, Drawable top, Drawable right, 
 Drawable bottom)

method with null for any that are not needed.

eyespyus
  • 1,576
  • 19
  • 20
  • 6
    I was able to do it with this: button_drill.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_button_green, 0); or should I use Drawables and turn my resource into a drawable? –  Sep 11 '11 at 19:49
  • 7
    Most probably you want to use `setCompoundDrawablesWithIntrinsicBounds`. With the other method you would have to call `setBounds` on the Drawables before passing them as parameters, otherwise they will not be rendered correctly (won't be visible at all) – janos Apr 28 '13 at 09:42
8

Usually you can change using this

Drawable draw = getResources().getDrawable(R.drawable.facebook);
myButton.setCompoundDrawablesWithIntrinsicBounds(null, null, draw, null);

Be aware you can miss the button text.

Paul Verest
  • 60,022
  • 51
  • 208
  • 332
luciano.bustos
  • 358
  • 2
  • 6