You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过代码清除Vector Drawable的着色(Tint)效果?

解决Vector Drawable的ImageView着色清除问题

问题原因

调用ImageViewCompat.setImageTintList(null)会让ImageView完全移除着色规则,如果你的Vector Drawable本身没有默认填充色(比如仅为轮廓样式),就会导致图片看起来消失。另外,clearColorFilter无法清除通过tintList设置的着色,因为二者属于不同的着色机制。

解决方案

核心思路是保存ImageView的初始着色状态,需要清除着色时,不是设为null,而是恢复到初始的ColorStateList。

代码实现

在RecyclerView的ViewHolder中,初始化时保存ImageView的原始tintList,点击时切换黄色着色或恢复原始状态:

class LightbulbViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    private val lightbulbIV: ImageView = itemView.findViewById(R.id.iv_lightbulb)
    // 保存初始着色状态,布局中未设置tint则为null(此时Drawable显示自身固有颜色)
    private val originalTint: ColorStateList? = ImageViewCompat.getImageTintList(lightbulbIV)

    init {
        lightbulbIV.setOnClickListener {
            val currentTint = ImageViewCompat.getImageTintList(lightbulbIV)
            val yellowColor = ContextCompat.getColor(itemView.context, R.color.yellow)
            
            // 判断当前是否为黄色着色
            val isYellow = currentTint?.defaultColor == yellowColor
            
            if (isYellow) {
                // 恢复原始着色
                ImageViewCompat.setImageTintList(lightbulbIV, originalTint)
            } else {
                // 设置黄色着色
                ImageViewCompat.setImageTintList(
                    lightbulbIV,
                    ColorStateList.valueOf(yellowColor)
                )
            }
        }
    }
}

额外说明

  1. 如果你的Vector Drawable本身有明确的默认颜色,也可以直接创建对应ColorStateList来恢复,比如:
// 假设默认颜色为黑色
val defaultTint = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.black))
  1. 不要混用tintList和colorFilter:通过ImageViewCompat设置的tint,必须用同系列的方法修改或恢复,clearColorFilter对其无效。

内容的提问来源于stack exchange,提问作者HukeLau_DABA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 02:25:29