Android中app:drawableStartCompat设置的矢量图标显示颜色异常问题
问题原因
你遇到的图标变色问题是AppCompat/MaterialComponents系列主题的默认特性导致的:
- 这类主题默认开启了Drawable自动着色逻辑,通过
app:drawableStartCompat加载的矢量图标,优先级最高的颜色来源是布局/代码中设置的tint属性,其次是主题默认的着色规则,矢量图XML中定义的fillColor优先级最低。 - 你当前的主题默认给TextView的关联Drawable设置了主色作为着色值,直接覆盖了你在
ic_back.xml中写的白色填充色,哪怕你单独给TextView设置了白色文字颜色,也不会自动同步到Drawable的着色上。
解决方案
方案1(最推荐,改造成本最低)
直接在当前的TextView布局中显式指定Drawable着色为白色,添加app:drawableTint="@android:color/white"属性即可,修改后的代码如下:
<TextView android:id="@+id/btnBack" style="@style/TextNormal" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center_vertical" android:background="?selectableItemBackgroundBorderless" android:padding="@dimen/_8sdp" android:text="@string/common_back" android:textColor="@android:color/white" app:drawableStartCompat="@drawable/ic_back" app:drawableTint="@android:color/white" />
方案2(全局关闭自动着色)
如果不需要全局自动给Drawable着色,可以在你的App主题定义中添加如下配置,之后所有矢量图都会默认使用自身XML中定义的填充色:
<style name="你的App主题名" parent="Theme.MaterialComponents/Theme.AppCompat.xxxx"> <!-- 其他原有配置 --> <item name="android:drawableTint">@null</item> </style>
方案3(代码动态设置)
也可以在页面代码中手动清除该图标的着色值:
// Kotlin 实现 val backBtn = findViewById<TextView>(R.id.btnBack) // 取start位置的drawable清除tint DrawableCompat.setTintList(backBtn.compoundDrawables[0], null)
// Java 实现 TextView backBtn = findViewById(R.id.btnBack); DrawableCompat.setTintList(backBtn.getCompoundDrawables()[0], null);
内容的提问来源于stack exchange,提问作者PhongBM
相关产品推荐
相关产品推荐

