有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java 安卓 Drawable getConstantState。newDrawable()与mutate()的比较

在安卓系统中,我读过几篇关于drawables如何共享恒定状态的文章。因此,如果您对drawable进行更改,它会影响所有相同的位图。例如,假设你有一个明星抽奖名单。改变一号上的alpha将改变所有的星星绘制alpha。但是你可以使用mutate来获得一个没有共享状态的drawable的副本
我读的那篇文章是here

现在谈谈我的问题:

安卓中的以下两个调用之间有什么区别:

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

// vs

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

对我来说,他们都在克隆一个drawable,因为他们都返回一个没有共享状态的drawable。我错过什么了吗


共 (1) 个答案

  1. # 1 楼答案

    正如@4castle在commentsmutate()中指出的那样,方法返回具有复制常量drawable状态的drawable的相同实例。医生说

    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