Android Widget中Vector类型ImageView的程序化着色问题
Android Widget中Vector ImageView着色问题解决办法
一、程序化着色(推荐动态场景)
由于Widget通过RemoteViews控制,无法直接调用ImageView的常规着色方法,需使用RemoteViews提供的专属API:
// 获取目标颜色对应的ColorStateList ColorStateList tintColor = ContextCompat.getColorStateList(context, R.color.colorPrimary); // 为指定ImageView设置着色 remoteViews.setImageViewTintList(R.id.item_plus_symbol, tintColor);
如果只需要单一固定颜色,也可以直接创建ColorStateList:
int solidColor = ContextCompat.getColor(context, R.color.colorPrimary); remoteViews.setImageViewTintList(R.id.item_plus_symbol, ColorStateList.valueOf(solidColor));
注意:该方式兼容API 21及以上,低版本可添加版本判断做兼容处理。
二、优化XML写法(静态着色更优雅)
用app:srcCompat替代android:src引用Vector资源,搭配android:tint就不会触发Lint的UseAppTint提示,无需添加ignore标签:
<ImageView android:id="@+id/item_plus_symbol" android:layout_width="16sp" android:layout_height="16sp" android:layout_marginStart="2dp" android:layout_marginTop="3dp" android:tint="@color/colorPrimary" app:srcCompat="@drawable/ic_plus_filled" />
app:srcCompat是AndroidX专门为Vector兼容设计的属性,和android:tint配合完全符合规范。
三、LayerList包装方案(不修改原资源)
如果不想写代码也不想改动原Vector资源,可以新建一个LayerList drawable来包装原资源并实现着色:
新建drawable/ic_plus_filled_tinted.xml文件:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/ic_plus_filled" android:tint="@color/colorPrimary" /> </layer-list>
然后在ImageView中引用这个新的drawable:
<ImageView android:id="@+id/item_plus_symbol" android:layout_width="16sp" android:layout_height="16sp" android:layout_marginStart="2dp" android:layout_marginTop="3dp" app:srcCompat="@drawable/ic_plus_filled_tinted" />
这种方式适合不需要动态切换颜色的场景,完全无需修改原Vector资源。
内容的提问来源于stack exchange,提问作者Franklin84
相关产品推荐
相关产品推荐

