android ColorStateList以编程方式创建并应用于TextColor

我正在尝试将通过代码创建的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);
点赞