【问题标题】:How to set the text_selector at the run time如何在运行时设置 text_selector
【发布时间】:2012-07-10 07:51:23
【问题描述】:

我正在使用以下选择器

text_selector.xml

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_selected="true" android:color="@android:color/white"/>
    <item android:state_focused="true" android:color="@android:color/white"/>
    <item android:state_pressed="true" android:color="@android:color/white"/>    
    <item android:color="@android:color/black" />
</selector>

我正在使用以下代码在运行时设置选择器

txtMainlabel.setTextColor(R.color.text_selector);

【问题讨论】:

标签: java android android-layout


【解决方案1】:

将你的选择器放在 res/drawable 下并使用

label.setTextColor(getResources().getColorStateList(R.drawable.text_selector));

不要忘记在布局中的 TextView 声明中设置 android:clickable="true"

【讨论】:

  • @V.P.查看更新的答案;)如果您不对文本视图使用深色背景,您的白色也可能不会出现
  • :-意思是?我听不懂你的回答
  • 我在静态内部类中设置了我的文本视图
【解决方案2】:
txtMainlabel.setTextColor(R.color.text_selector);

setTextColor 需要一个与颜色值对应的整数。您正在做的是用整数值 R.color.text_selector 赋予颜色。您可以在 R 文件中看到该值。因此,您始终为视图设置相同的颜色。

要设置颜色,您可以:setTextColor(Color.white)

我也不确定 TextView 是否有状态,所以我不确定您是否可以将选择器设置为 TextView。如果这不是一个选项,您始终可以设置点击侦听器并为这些操作设置新颜色。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-09
    • 2012-04-10
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 2019-06-16
    • 2018-01-13
    相关资源
    最近更新 更多