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