j2e*_*nue 12 android android-drawable
在android中我已经阅读了一些关于drawable如何共享一个常量状态的文章.因此,如果您对drawable进行更改,则会影响所有相同的位图.例如,假设你有一个明星可绘制的列表.更改一个alpha将改变所有星形drawables alpha.但是您可以使用mutate来获取没有共享状态的drawable副本.
我正在阅读的文章就在这里
现在我的问题:
android中以下两个调用之间有什么区别:
Drawable clone = drawable.getConstantState().newDrawable();
// vs
Drawable clone = (Drawable) drawable.getDrawable().mutate();
Run Code Online (Sandbox Code Playgroud)
对我来说,他们都克隆了一个drawable,因为他们都返回了一个没有共享状态的drawable.我错过了什么吗?
Kir*_*ill 13
正如@ 4castle在comments中指出的mutate()方法返回与复制的常量drawable状态相同的drawable实例.Docs说
一个可变的drawable保证不与任何其他drawable共享其状态
因此,在不影响具有相同状态的drawable的情况下更改drawable是安全的
让我们玩这个drawable - 黑色的形状
<!-- shape.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@android:color/black" />
</shape>
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
相反的方法是newDrawable().它创建了一个新的drawable但具有相同的常量状态.比如看BitmapDrawable.BitmapState:
@Override
public Drawable newDrawable() {
return new BitmapDrawable(this, null);
}
Run Code Online (Sandbox Code Playgroud)
对新drawable的更改不会影响当前drawable,但会更改状态:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3186 次 |
| 最近记录: |