How can I set the drawableRight resource via code?

2020-02-10 15:15发布

问题:

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?

回答1:

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.



回答2:

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.