【问题标题】:Setting background colour on one object, changes another object在一个对象上设置背景颜色,更改另一个对象
【发布时间】:2013-03-20 17:13:54
【问题描述】:

我有一个以可绘制为背景的 TextView。使用 StateListDrawable 对象,我尝试以编程方式设置背景颜色,但遇到了意想不到的行为:我在一个对象中设置了颜色,而在另一个对象中它发生了变化。这应该是不可能的。

相关代码:

    GradientDrawable notPressed = (GradientDrawable) getResources().getDrawable(R.drawable.rectangle);
    GradientDrawable isPressed = (GradientDrawable) getResources().getDrawable(R.drawable.rectangle);
    isPressed.setColor(util.getColour(api, this));

    StateListDrawable bg = new StateListDrawable();
    // bg.addState(new int[] { android.R.attr.state_pressed }, isPressed);
    bg.addState(StateSet.WILD_CARD, notPressed);

    textView.setBackgroundDrawable(bg);

可绘制对象:

<shape  xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
<stroke android:width="1dp" android:color="@color/divider" />
<solid android:color="@color/background_button" />
</shape>

util.getColour根据api的值返回颜色资源。

奇怪的是,在上面的代码中,isPresseddrawable 的颜色被设置了,但是之后这个 drawable 就没有被使用了。相反,只有notPressed drawable 被添加到 textView 的背景中。

但是textView的背景颜色变成了isPresseddrawable的颜色!这应该是不可能的,因为它们应该是两个不同的对象,即使它们是从同一个可绘制资源创建的。

【问题讨论】:

  • 检查notPressed!=isPressed是否是同一个对象。

标签: java android android-resources android-drawable


【解决方案1】:

我认为,当您获得资源时,您会得到相同的引用。所以notPressedisPressed 是同一个对象。我相信某处有克隆操作...

编辑:

是的,在你修改它之前,你必须在drawable上调用mutate()。见Adding a color filter to a Drawable changes all Buttons using the same Drawable

【讨论】:

    【解决方案2】:

    Android 对可绘制资源使用相同的对象,除非您指定需要它的新副本。

    您可以使用此代码来解决此问题:

    Drawable isPressed  = notPressed.getConstantState().newDrawable();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多