Android 按压时降低透明度, 不用替换图片

发布时间 2023-06-19 14:36:59作者: 勤奋的小铁

只需要自定义控件监听 dispatchSetPressed 方法就可以轻松实现 比如:

class ImageViewButton(context: Context, attrs: AttributeSet?, defStyleAttr: Int):
    androidx.appcompat.widget.AppCompatImageView(context, attrs, defStyleAttr) {
    constructor(context: Context) : this(context, null, 0)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    override fun dispatchSetPressed(pressed: Boolean) {
        this.alpha = if(pressed) 0.3f else 1f
        super.dispatchSetPressed(pressed)
    }

}

比传统的 selector 监听 state_pressed而言不仅 简直是一劳永逸