如何用十六进制值更改CheckedTextView的Checked Tint Color

我想在checked视图的状态时动态地改变CheckedTextView的色调。 我很确定我可以通过在CheckedTextView上调用setCheckMarkTintList来实现这CheckedTextView 。 要做到这一点,我需要一个ColorStateList ,但问题是我想保留CheckedTextView每个状态的所有颜色,除了checked状态。

所以,我可以获得ColorStateListCheckedTextView ,但是我不知道只能更改checked状态的颜色。 我知道我可以创建一个新的ColorStateList ,但是如何确保它保留了原始的所有值?

我可以像这样创建一个状态列表:

 int[][] states = new int[][] { new int[]{android.R.attr.state_pressed}, new int[]{-android.R.attr.state_pressed}, new int[]{android.R.attr.state_focused}, new int[]{-android.R.attr.state_focused}, new int[]{android.R.attr.state_selected}, new int[]{-android.R.attr.state_selected}, new int[]{android.R.attr.state_checkable}, new int[]{-android.R.attr.state_checkable}, new int[]{android.R.attr.state_checked}, new int[]{-android.R.attr.state_checked}, new int[]{android.R.attr.state_enabled}, new int[]{-android.R.attr.state_enabled}, new int[]{android.R.attr.state_window_focused}, new int[]{-android.R.attr.state_window_focused}, new int[]{} // default state } 

并从原始ColorStateList的颜色创建一个颜色列表:

 int[] colors = new int[] { stateList.getColorForState(new int[]{android.R.attr.state_pressed}, stateList.getDefaultColor()), stateList.getColorForState(new int[]{-android.R.attr.state_pressed}, stateList.getDefaultColor()), stateList.getColorForState(new int[]{android.R.attr.state_focused}, stateList.getDefaultColor()), stateList.getColorForState(new int[]{-android.R.attr.state_focused}, stateList.getDefaultColor()), stateList.getColorForState(new int[]{android.R.attr.state_selected}, stateList.getDefaultColor()), stateList.getColorForState(new int[]{-android.R.attr.state_selected}, stateList.getDefaultColor()), stateList.getColorForState(new int[]{android.R.attr.state_checkable}, stateList.getDefaultColor()), stateList.getColorForState(new int[]{-android.R.attr.state_checkable}, stateList.getDefaultColor()), Color.parseColor(colorHexValue), stateList.getColorForState(new int[]{-android.R.attr.state_checked}, stateList.getDefaultColor()), stateList.getColorForState(new int[]{android.R.attr.state_enabled}, stateList.getDefaultColor()), stateList.getColorForState(new int[]{-android.R.attr.state_enabled}, stateList.getDefaultColor()), stateList.getColorForState(new int[]{android.R.attr.state_window_focused}, stateList.getDefaultColor()), stateList.getColorForState(new int[]{-android.R.attr.state_window_focused}, stateList.getDefaultColor()), stateList.getDefaultColor() } 

但是这只会覆盖孤立的状态……你也可以组合状态,比如new int[]{android.R.attr.state_enabled, android.R.attr.state_pressed, -android.R.attr.state_checked} 。 试图解释每个可能的状态是荒谬的,那么我怎么可能知道原始的ColorStateList已经设置了什么状态呢? 有没有更简单的方法来做到这一点? 我是否过度了?

它看起来像在CheckedTextView着色是非常错误的。 最后,我通过在onClickListener交换颜色来解决它:

 checkedTextView.setOnClickListener { if (checkedTextView.isChecked) { checkedTextView.checkMarkTintList = ColorStateList.valueOf(color1) } else { checkedTextView.checkMarkTintList = ColorStateList.valueOf(color2) } } 

(例如在Kotlin中,Java是相似的)