[英]How to change background/color of the drawable set as background of a view?
[英]How to change the background color of a View Drawable without changing its body in recyclerView?
我有一个带有主体和颜色的标准可绘制对象。 但是每当我调用方法recyclerView
holder.item.setBackgroundColor ();
或setBackground
它甚至会根据需要更改颜色,但最终会完全改变我最初的 drawble 的形状。
我的形状 Drawble:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@android:color/holo_orange_dark" />
<size
android:width="120dp"
android:height="120dp"
/>
</shape>
实现形状的视图
<?xml version="1.0" encoding="utf-8"?>
<View
android:id="@+id/item_cores"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@drawable/cores_drawable"
android:layout_margin="10dp"
android:backgroundTint="@color/black"
xmlns:android="http://schemas.android.com/apk/res/android" />
class 支架
class coresHolder extends RecyclerView.ViewHolder {
cores colors;
View item;
public coresHolder(View itemView) {
super(itemView);
itemClick(itemView);
item= itemView.findViewById(R.id.item_cores);
}
private void itemClick(View itemView) {
itemView.setOnClickListener(v -> {
onClickListernet.onItemClick(colors);
});
}
public void vincule(cores colors) {
this.colors =colors;
}
}
// bind
@Override
public void onBindViewHolder(coresHolder holder, int position) {
cores cores=list.get(position);
holder.vincule(cores);
//ps only a test change color to holder
holder.item.setBackgroundColor(R.color.purple_700);
我需要的:
我得到了什么:
在适配器中添加以下实用程序方法
public static void setDrawableColor(Context context, Drawable drawable, int color) {
Drawable drawableWrap = DrawableCompat.wrap(drawable).mutate();
DrawableCompat.setTint(drawableWrap, ContextCompat.getColor(context, color));
}
并在onBindViewHolder
中按如下方式使用
@Override
public void onBindViewHolder(coresHolder holder, int position) {
cores cores=list.get(position);
holder.vincule(cores);
// Changing background drawable
setDrawableColor(holder.item.getContext(), holder.item.getBackground(), R.color.purple_700);
}
演示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.