android 可绘制 - getConstantState.newDrawable() 与 mutate()

android Drawable - getConstantState.newDrawable() vs mutate()

在 android 中,我阅读了一些关于可绘制对象如何共享常量状态的文章。因此,如果您对可绘制对象进行更改,它会影响所有相同的位图。例如,假设您有一个星形可绘制对象列表。改变其中一个的 alpha 会改变所有星星 drawables 的 alpha。但您可以使用 mutate 获取您自己的没有共享状态的可绘制对象副本。
我正在阅读的文章是 here

现在开始我的问题:

下面两个调用在android中有什么区别:

Drawable clone = drawable.getConstantState().newDrawable();

// vs

Drawable clone = (Drawable) drawable.getDrawable().mutate();

对我来说,它们都在克隆一个可绘制对象,因为它们都return 一个没有共享状态的可绘制对象。我错过了什么吗?

正如@4castle 在评论中指出的那样mutate() 方法returns 具有复制的常量可绘制对象状态的可绘制对象的相同实例。文档说

A mutable drawable is guaranteed to not share its state with any other drawable

因此可以安全地更改可绘制对象而不影响具有相同状态的可绘制对象

让我们玩这个可绘制的东西 - 黑色形状

 <!-- shape.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@android:color/black" />
</shape>


view1.setBackgroundResource(R.drawable.shape); // set black shape as a background
view1.getBackground().mutate().setTint(Color.CYAN); // change black to cyan
view2.setBackgroundResource(R.drawable.shape); // set black shape background to second view


相反的方法是newDrawable()。它创建了一个新的可绘制对象,但具有相同的常量状态。例如。看看 BitmapDrawable.BitmapState:

    @Override
    public Drawable newDrawable() {
        return new BitmapDrawable(this, null);
    }

对新绘图的更改不会影响当前绘图,但会更改状态:

view1.setBackgroundResource(R.drawable.shape); // set black shape as background
Drawable drawable = view1.getBackground().getConstantState().newDrawable();
drawable.setTint(Color.CYAN); // view still black
view1.setBackground(drawable); // now view is cyan
view2.setBackgroundResource(R.drawable.shape); // second view is cyan also