我正在尝试将通过代码创建的 ColorStateList 应用为 TextView 的 TextColor。 问题是,如果我使用在 xml 中定义的 ColorStateList,它会起作用,但当我通过代码创建 ColorStateList 时不起作用。
下面是我如何创建 ColorStateList
int[][] states = new int[][] { new int[] { android.R.attr.state_activated } };
int[] colors = new int[] { Color.parseColor("#FFFF00") };
myList = new ColorStateList(states, colors);
我以这种方式简单地将它应用到 TextView
myTextView.setTextColor(myList);
并且不起作用。使用这个 xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true" android:color="@color/yellow" />
<item android:color="@color/black" />
</selector>
它既可以在 xml 中设置文本颜色,也可以通过代码以这种方式工作
myTextView.setTextColor(myTextView.getContext().getResources().getColorStateList(R.drawable.textcolor_selector));
我在网上搜索了解决方案,但我真的找不到导致这个问题的原因,谁能帮帮我?
谢谢
最佳答案
也许您应该在状态列表中添加一个默认值。在你的例子中,state_activated 的相反状态:
int[][] states = new int[][] { new int[] { android.R.attr.state_activated }, new int[] { -android.R.attr.state_activated } };
int[] colors = new int[] { Color.parseColor("#FFFF00"), Color.BLACK };
myList = new ColorStateList(states, colors);
关于android ColorStateList 以编程方式创建并应用于 TextColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21605392/