gpt4 book ai didi

java - setColorFilter 应用于所有按钮

转载 作者:太空宇宙 更新时间:2023-11-04 12:55:17 25 4
gpt4 key购买 nike

我有一个扩展按钮 View 的类,我用它来创建自定义形状的按钮,例如十六进制按钮,并且仅响应实际按钮区域的点击,而不响应 View 的默认矩形形状。然而,这部分工作正常,我还希望能够更改按钮的颜色,而无需为每种颜色创建不同的可绘制对象,因此我使用带有灰度阴影的白色创建了按钮图像,并使用 setColorFilter 设置我从 xml 中读取的颜色,它工作得很好,除了当 Activity 启动或重新启动时,所有按钮都会获取最后一个按钮(最后创建或单击)的颜色。单击按钮手动设置正确的颜色,但是当更改 Activity 并返回时,所有按钮都会获取最后按下的按钮的颜色。

这是我初始化颜色的地方:

@Override
protected void onFinishInflate() {
super.onFinishInflate();
// Set the button background and color
updateButton(normalButton);
}

private void updateButton(Drawable background) {
if (background == null) return;
//Set button background
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
this.setBackground(background);
} else {
//noinspection deprecation
this.setBackgroundDrawable(background);
}
this.getBackground().setColorFilter(buttonColor, PorterDuff.Mode.MULTIPLY);
//this.setBackgroundColor(buttonColor);
}

函数 updateButton() 也用于 onTouch() 方法中,以在按下状态和正常状态之间切换可绘制对象。当按下任何按钮时,它会起作用并设置正确的颜色。

如果我使用 this.setBackgroundColor(buttonColor); 着色可以找到(但它会覆盖图像),但是,setColorFilter 无法按我想要的方式工作。

有人可以帮我解决这个问题吗?

这是整个代码的链接 ( link on github )

enter image description here

这张图说明了问题,左边是启动时的样子,右边是应该的样子。

最佳答案

我找到了答案。在应用滤色器之前我需要改变可绘制对象。

myDrawable = myDrawable.mutate();
myDrawable.setColorFilter(buttonColor, PorterDuff.Mode.MULTIPLY);

关于java - setColorFilter 应用于所有按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35446073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com