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

标签 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));

我在网上搜索了解决方案,但我真的找不到导致这个问题的原因,谁能帮帮我?

谢谢

最佳答案

也许您应该在状态列表中添加一个默认值。在你的例子中,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/

相关文章:

android - PhoneGap + jQuery Mobile = 缓慢的点击响应时间

android - 以编程方式将特定颜色设置为 ColorStateList

带有圆角的 Android SlidingTabs 样式选项卡

android - RecyclerView 选择器中的 ConstraintLayout

java - 如何在 fragment 内制作抽屉导航?

java - 在前一个 TextView 下添加另一个 TextView 作为第二个 TextView

ios - 在 Swift 中更改 UITextView 的 textColor

swift - 更改字符串数组中特定文本的颜色。 swift

android - 如何从 API 23+ 中的可绘制选择器设置 alpha?

Android:当文件名有空格时设置文件权限时出现问题