【问题标题】:How can I set the drawableRight resource via code?如何通过代码设置 drawableRight 资源?
【发布时间】:2011-09-11 19:10:15
【问题描述】:

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

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

【问题讨论】:

  • 你说的横向变化是什么意思?,在按钮点击之前,你的图片是在按钮的左侧吗?
  • 它在右侧,是一个红点。我想在点击时将其更改为绿色。 (这是一个切换按钮)
  • setCompoundDrawablesWithIntrinsicBounds 相关问题:stackoverflow.com/questions/4250923/…

标签: android button drawable


【解决方案1】:

你需要使用

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

任何不需要的方法都为 null。

【讨论】:

  • 我能够做到这一点:button_drill.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_button_green, 0);还是我应该使用 Drawables 并将我的资源变成一个 drawable?
  • 很可能你想使用setCompoundDrawablesWithIntrinsicBounds。使用另一种方法时,您必须先在 Drawables 上调用 setBounds,然后再将它们作为参数传递,否则它们将无法正确呈现(根本不可见)
【解决方案2】:

通常你可以用这个来改变

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

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

【讨论】:

    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 2015-01-22
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多