Issue
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:
Solution
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:
Answered By - Zain
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.