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

12

我试图在按钮被点击后通过代码将一张图片设置在按钮的右侧。我想要通过代码完成这个操作。

我看到了如何通过代码更改背景资源,但是我找不到任何示例展示如何通过代码更改边缘。这是否可能?


什么是侧面改变?按钮点击之前,您的图像是否在按钮左侧? - Yashwanth Kumar
它在右侧,是一个红点。我想在点击时将其变为绿色。(这是一个切换按钮) - user427390
4
setCompoundDrawablesWithIntrinsicBounds 的意思是在一个文本视图或按钮控件上设置左、上、右、下四个方向的图标。 - Erdal
2个回答

28
您需要使用HTML元素``来保留代码。
public void setCompoundDrawables (Drawable left, Drawable top, Drawable right, 
 Drawable bottom)

对于不需要的参数,可以使用null作为方法参数。


6
我可以用这个实现:button_drill.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_button_green, 0); 或者我应该使用Drawables并将我的资源转换成一个drawable?请问您需要哪个翻译? - user427390
7
很可能你想要使用setCompoundDrawablesWithIntrinsicBounds这个方法。如果你使用另外一个方法,就必须在将Drawable对象传递为参数之前调用setBounds方法,否则它们将无法正确地渲染(完全不可见)。 - janos

8
通常您可以使用以下方式进行更改:
Drawable draw = getResources().getDrawable(R.drawable.facebook);
myButton.setCompoundDrawablesWithIntrinsicBounds(null, null, draw, null);

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接