如何获取动态按钮的十六进制颜色值?
如何获取Android按钮的实时背景色并做条件判断
嘿,我太懂你这个困扰了!设置按钮的十六进制颜色很顺手,但要获取它的实时颜色来写if判断确实容易踩坑。你之前的两种尝试都没找对正确的对比方式,我来给你捋清楚正确的做法:
先说说你之前方法的问题
- 第一种方法里,你拿到了
ColorDrawable对象,但直接把它和字符串"#FFFFFF"对比肯定不对——一个是对象,一个是字符串,类型都不一样,怎么可能相等呢?你得从ColorDrawable里取出实际的颜色数值再对比。 - 第二种方法里,
button.getResources().getString(R.color.notPresent)是错误的用法!颜色资源本质是int类型的色值,不是字符串,你用getString拿不到正确的颜色数值,自然没法判断。
正确的实现方式
方法一:直接对比十六进制转成的色值
先获取按钮的背景,判断是不是ColorDrawable(避免非纯色背景导致崩溃),然后取出它的int色值,再和目标颜色的int值对比:
// 获取按钮背景 Drawable buttonBackground = button.getBackground(); // 先判断背景是否为纯色的ColorDrawable if (buttonBackground instanceof ColorDrawable) { // 取出当前按钮的颜色int值 int currentButtonColor = ((ColorDrawable) buttonBackground).getColor(); // 把目标十六进制颜色转成int值 int targetWhiteColor = Color.parseColor("#FFFFFF"); // 现在可以直接对比色值了 if (currentButtonColor == targetWhiteColor) { // 这里写你要执行的逻辑 // do stuff } }
方法二:用colors.xml里定义的颜色资源
如果你想用资源文件里的颜色来对比,要先获取资源对应的int色值,再和按钮的颜色值对比:
// 获取colors.xml里定义的颜色int值(API23+建议用ContextCompat兼容) int targetColor = ContextCompat.getColor(this, R.color.notPresent); Drawable buttonBackground = button.getBackground(); if (buttonBackground instanceof ColorDrawable) { int currentButtonColor = ((ColorDrawable) buttonBackground).getColor(); if (currentButtonColor == targetColor) { // 执行你的逻辑 } }
额外注意事项
- 如果你的按钮背景不是纯色(比如是渐变、选择器Drawable),那上面的方法会失效,这时候你需要针对对应的Drawable类型做处理——不过如果只是简单的纯色切换,
ColorDrawable的判断就足够了。 - 颜色的int值包含alpha通道,如果你设置的颜色没写alpha(比如
#FFFFFF实际是#FFFFFFFF),要是遇到alpha不同的情况,可以忽略alpha通道对比:(currentButtonColor & 0xFFFFFF) == (targetColor & 0xFFFFFF)
内容的提问来源于stack exchange,提问作者Display name
相关产品推荐
相关产品推荐

