gpt4 book ai didi

android - 颜色/可绘制更改应用于具有相同背景(颜色)的所有 View [Marshmallow]

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:58:33 27 4
gpt4 key购买 nike

我最近将我的手机更新为 Android Marshmallow 并在其上运行了我现有的应用程序,但注意到颜色行为有所不同:将更改应用到 View (可绘制)的背景时,共享相同背景的所有 View (引用)也将应用相同的更改。而以前,情况并非如此。

例子
在此示例中,我有两个具有相同背景颜色的 View ,我想更改其中一个 View 的 alpha 级别。

首先我们定义布局中的 View :

    <LinearLayout
android:id="@+id/test1"
android:orientation="horizontal"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@color/testColor2">

</LinearLayout>

<LinearLayout
android:id="@+id/test2"
android:orientation="horizontal"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@color/testColor1"
android:layout_marginLeft="5dp">
</LinearLayout>

两个 View 共享相同的背景颜色或可绘制对象:

<color name="testColor1">#3F51B5</color>
<color name="testColor2">#3F51B5</color>

结果是这样的:
enter image description here

现在我们要改变两个背景之一,像这样:

    LinearLayout test1 = (LinearLayout) findViewById(R.id.test1);
LinearLayout test2 = (LinearLayout) findViewById(R.id.test2);
test1.getBackground().setAlpha(80);

结果是:
enter image description here

然而,期望和预期的结果显然是这样的:
enter image description here

下载示例项目 here.

几点思考:

  • 通过 XML 设置 Alpha 级别时,此行为不适用。
  • 如果两个 View 在 colors.xml 中引用不同的颜色定义(如示例中)并不重要,请直接在 View 的 xml 文件中引用相同颜色(十六进制)的相同颜色定义。

问题
如何在不影响共享相同背景的其他 View 的情况下更改 View 的背景。 最好仍然能够使用直接引用颜色 xml 文件中定义的颜色的背景

最佳答案

Most likely the class of each view's background and constantstate arethe same object. It seems as if the two color resources have been"merged" somewhere -- meaning they have shared ConstantState. Maybe inthe Resources class' caching? I would've expected them to stayseparate since they're different resources (albeit with the same colorvalue), but apparently not.

Snild Dolkow

ColorDrawable 的状态存储 alpha,因此对其中一个的任何更改都会更改其他。为防止这种情况发生,您可以先在可绘制对象上调用 mutate(),将两个可绘制对象分开(通过复制状态)。

在示例中,这将导致使用 test1.getBackground().mutate().setAlpha(80); 而不是直接应用 alpha。

关于android - 颜色/可绘制更改应用于具有相同背景(颜色)的所有 View [Marshmallow],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33354788/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com