在安卓开发中,常需要根据数据状态动态调整颜色,
实现方式 | 适用场景 | 优点 | 缺点 |
---|---|---|---|
直接调用setColorFilter() | 单个视图颜色修改 | 简单快速 | 破坏原有绘制效果 |
使用ColorStateList | 按钮等交互控件 | 支持多状态 | 需定义xml资源 |
数据绑定+android:textColor | TextView颜色绑定 | 解耦逻辑 | 需配合LiveData |
自定义RecyclerView.Adapter | 列表项多色渲染 | 灵活控制 | 需处理复用问题 |
场景:RecyclerView列表根据温度值显示不同背景色
// 在Adapter的onBindViewHolder中 int temperature = dataList.get(position).getTemperature(); if (temperature > 35) { holder.itemView.setBackgroundColor(ContextCompat.getColor(context, R.color.red_500)); } else if (temperature < 0) { holder.itemView.setBackgroundColor(ContextCompat.getColor(context, R.color.blue_500)); } else { holder.itemView.setBackgroundColor(Color.WHITE); }
XML布局配置渐变色:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="温度值" android:textColor="@color/selector_temperature_color"/>
res/color/selector_temperature_color.xml
:
<selector> <item android:color="@color/red_500" android:state_active="true"/> <item android:color="@color/blue_500" android:state_active="false"/> </selector>
Resources.Theme
动态更换颜色资源ValueAnimator
实现颜色渐变过渡AccessibilityManager
调整高对比度模式A:
使用RippleDrawable
叠加层实现点击反馈:
<item android:id="@android:id/mask"> <shape android:shape="rectangle"> <solid android:color="@android:color/black"/> </shape> </item> <item> <color android:color="@color/item_background"/> <!-保持原有背景色 --> </item>
在XML布局中设置android:background="@drawable/ripple_background"
,并在代码中保持itemView.setClickable(true)
。
A:
RecyclerView.Adapter
的@NonNull
机制避免重复创建视图 private final int[] colorCache = new int[4];
DiffUtil
计算最小变更范围 doInBackground
线程,仅最终颜色值回主线程