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

时间:2014-02-06 14:18:05

标签: android textcolor android-selector

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

我在网上搜索了一个解决方案,但我真的找不到导致这个问题的原因,有人可以帮帮我吗?

谢谢

1 个答案:

答案 0 :(得分:2)

也许您应该在状态列表中添加默认值。在您的情况下,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);
相关问题