如何恢复setTint()设置后控件的默认色调?
解决View禁用/启用时的色调恢复问题
核心问题:background.setTint(Color.GRAY) 是给背景设置了ColorStateList,而非ColorFilter,所以调用clearColorFilter()完全不会影响这个设置,自然没效果。
下面是靠谱的实现思路和代码:
- 先保存View原始的背景色调(ColorStateList),第一次禁用时存下来就行
- 禁用时设置灰色的ColorStateList,启用时把原始的ColorStateList设回去
代码示例(Java)
// 给View扩展方法,先声明变量存原始色调 private ColorStateList originalBgTint; public void disable() { // 首次禁用时保存原始色调 if (originalBgTint == null) { originalBgTint = getBackground().getTintList(); } // 设置灰色背景 getBackground().setTintList(ColorStateList.valueOf(Color.GRAY)); setEnabled(false); // 顺手把View的enabled状态设为false,符合交互逻辑 } public void enable() { // 恢复原始色调 if (originalBgTint != null) { getBackground().setTintList(originalBgTint); } setEnabled(true); }
更省心的原生方案
如果你的View(比如Button)本身有状态选择器背景,其实不用自己写enable/disable方法,直接给背景设置带状态的ColorStateList,之后调用setEnabled(true/false)就能自动切换颜色:
// 初始化时设置状态关联的色调 ColorStateList tintStateList = new ColorStateList( new int[][]{ new int[]{-android.R.attr.state_enabled}, // 禁用状态 new int[]{android.R.attr.state_enabled} // 启用状态 }, new int[]{ Color.GRAY, // 禁用时显示灰色 getResources().getColor(R.color.your_original_color) // 启用时显示原色调 } ); getBackground().setTintList(tintStateList);
这样之后只要调用setEnabled(),背景色就会自动跟着状态变,不用自己维护enable/disable方法。
内容的提问来源于stack exchange,提问作者ultrapoci
相关产品推荐
相关产品推荐

