简体   繁体   中英

How to change the background color of a View Drawable without changing its body in recyclerView?

I have a standard drawable with a body and a color. but I'm having trouble changing the color of this drawable in the Bind process of my recyclerView , whenever I invoke the method holder.item.setBackgroundColor (); or setBackground it even changes the color as needed, but it ends up totally changing the shape of my initial drawble.

My shape 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>

the view that implements the 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 holder

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);

What I need:

在此处输入图像描述

What I got:

在此处输入图像描述

Add the below utility method in the adapter

public static void setDrawableColor(Context context, Drawable drawable, int color) {
    Drawable drawableWrap = DrawableCompat.wrap(drawable).mutate();
    DrawableCompat.setTint(drawableWrap, ContextCompat.getColor(context, color));
}

And use it as follows in 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);
    
}

Demo:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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