可在适配器中动态绘制的Tint可更改所有对象的颜色 [英] Dynamically Tint drawable in adapter change color for all
问题描述
我使用齐射连接从服务器中获取字符串数组.每个字符串都以十六进制包含不同的颜色.我使用这种颜色在适配器中设置可绘制的色调.
I get an array of strings from my server using a volley connection. Every single string contain a different color in hex. I use this color to set Tint of a drawable in adapter.
这是我在适配器中的代码:
Here my code in adapter:
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
// Get item from position
MyObject object = array_data.get(position);
...
...
Drawable unwrappedDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_beenhere_black_24dp);
Drawable wrappedDrawable;
if (unwrappedDrawable != null) {
wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable);
DrawableCompat.setTint(wrappedDrawable, object.getMyColor());
holder.imvPreparationTime.setImageDrawable(wrappedDrawable);
}
不幸的是,该行为是不正确的. recyclerview中所有可绘制的项目具有相同的颜色,并且在滚动过程中所有颜色都会改变.
Unfortunately the behavior is not correct. All drawable of items in recyclerview have the same color together and it change for all during scroll.
我该如何实现目标?我希望每件商品都有自己的颜色而不要改变.
How can I perform my goal? I want that every items have his own color and not change.
推荐答案
这可以使用Drawable.mutate()
完成.在您的适配器类的onBindViewHolder(..)块中,使用下面的代码片段更改可绘制对象的颜色-
This can be done using Drawable.mutate()
. In your adapter class, onBindViewHolder(..) block, use below code snippet to change the tint color of your drawable -
for (Drawable drawable : myTextView.getCompoundDrawablesRelative()) {
if (drawable != null) {
Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
Drawable mutableDrawable = wrappedDrawable.mutate();
DrawableCompat.setTint(mutableDrawable, ContextCompat.getColor(context, R.color.desiredColor));
}
}
注意:此代码段用于更改textview的drawable的色彩.因此,如果您需要更改图像或可绘制文件的色彩,只需按以下步骤操作即可:
Note : This code snippet I've used to change the tint of textview's drawable. So, if you required to change the tint of image or drawable file, simply do it as :
Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
Drawable mutableDrawable = wrappedDrawable.mutate();
DrawableCompat.setTint(mutableDrawable, ContextCompat.getColor(context, R.color.colorGrayD5));
快乐编码!
这篇关于可在适配器中动态绘制的Tint可更改所有对象的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!