在
android中我读过一些关于drawables如何共享一个常量状态的文章.因此,如果您对drawable进行更改,则会影响所有相同的位图.例如,假设您有一个明星可绘制的列表.更改一个alpha将改变所有星形drawables alpha.但是您可以使用mutate来获取没有共享状态的drawable副本.
我正在阅读的文章是 here
我正在阅读的文章是 here
现在我的问题:
android中以下两个调用之间有什么区别:
Drawable clone = drawable.getConstantState().newDrawable(); // vs Drawable clone = (Drawable) drawable.getDrawable().mutate();
对我来说,他们都克隆了一个drawable,因为他们都返回了一个没有共享状态的drawable.我错过了什么吗?
解决方法
正如@ 4castle在注释中指出的,mutate()方法返回与复制的常量drawable状态相同的drawable实例. Docs说
A mutable drawable is guaranteed to not share its state with any other 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>
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().它创建了一个新的drawable但具有相同的常量状态.例如.看看BitmapDrawable.BitmapState:
@Override public Drawable newDrawable() { return new BitmapDrawable(this,null); }
对新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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。