如何通过代码设置drawableRight资源?

12 android button drawable

单击按钮后,我试图在按钮的右侧设置图像.我想通过代码来做到这一点.

我已经看到如何通过代码更改后台资源,但我无法找到任何显示如何通过代码更改侧面的示例.可能吗?

eye*_*yus 28

你需要使用

public void setCompoundDrawables (Drawable left, Drawable top, Drawable right, 
 Drawable bottom)
Run Code Online (Sandbox Code Playgroud)

对于任何不需要的方法,使用null的方法.

  • 很可能你想使用`setCompoundDrawablesWithIntrinsicBounds`.使用另一种方法,你必须在将它们作为参数传递之前在Drawables上调用`setBounds`,否则它们将无法正确呈现(根本不可见) (7认同)
  • 我能够做到这一点:button_drill.setCompoundDrawablesWithIntrinsicBounds(0,0,R.drawable.ic_button_green,0); 或者我应该使用Drawables并将我的资源变成一个可绘制的? (6认同)

小智 8

通常您可以使用此更改

Drawable draw = getResources().getDrawable(R.drawable.facebook);
myButton.setCompoundDrawablesWithIntrinsicBounds(null, null, draw, null);
Run Code Online (Sandbox Code Playgroud)

请注意,您可能会错过按钮文字.