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

Android 如何通过代码设置drawableRight资源?,android,button,drawable,Android,Button,Drawable,我试图在点击按钮后在按钮的右侧设置一个图像。我想通过代码来实现这一点 我已经看到了如何通过代码更改背景资源,但我找不到任何示例显示如何通过代码更改侧面。可能吗?您需要使用 public void setCompoundDrawables (Drawable left, Drawable top, Drawable right, Drawable bottom) 方法,对于不需要的任何对象都使用null。通常您可以使用此 Drawable draw = getResources().getD

我试图在点击按钮后在按钮的右侧设置一个图像。我想通过代码来实现这一点

我已经看到了如何通过代码更改背景资源,但我找不到任何示例显示如何通过代码更改侧面。可能吗?

您需要使用

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

方法,对于不需要的任何对象都使用null。

通常您可以使用此

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

请注意,您可能会错过按钮文本。

侧边更改是什么意思?在按钮单击之前,您的图像是否位于按钮的左侧?它位于右侧,是一个红点。我想按一下就把它变成绿色。(这是一个切换按钮)SetCompoundDrawableSwithinInsicBounds相关问题:我可以用这个按钮来做:button\u drill.SetCompoundDrawableSwithinInsicBounds(0,0,R.drawable.ic\u按钮\u green,0);或者我应该使用Drawables并将我的资源转换为Drawables吗?很可能您想要使用
setCompoundDrawablesWithIntrinsicBounds
。使用另一种方法时,在将其作为参数传递之前,您必须在绘图表上调用
setBounds
,否则它们将无法正确渲染(根本不可见)