繁体   English   中英

如何在不改变 recyclerView 主体的情况下更改 View Drawable 的背景颜色?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM