【问题标题】:Setting TextView color to a <selector> programmatically以编程方式将 TextView 颜色设置为 <selector>
【发布时间】:2011-04-12 23:40:52
【问题描述】:

我在 res/color/redeemlist_item_color.xml 下的 XML 文件中定义了以下选择器:

<?xml version="1.0" encoding="utf-8"?>
   <selector xmlns:android="http://schemas.android.com/apk/res/android">

      <item android:state_pressed="true"
            android:color="#FFFFFF" /> <!-- pressed -->

      <item android:state_selected="true"
            android:color="#FFFFFF" /> <!-- focused -->

      <item android:color="#000000" /> <!-- default -->

   </selector>

我在ListView 项目布局中也有一个TextView。 When I set android:textColor on this TextView to the above selector in XML, then the color changes correctly when the item is selected.但是,我正在尝试通过以下方式以编程方式设置此资源:

holder.label.setTextColor(R.color.redeemlist_item_color);

以这种方式设置时,颜色不再改变。可以通过这种方式将选择器分配给TextView吗?

【问题讨论】:

    标签: android android-resources


    【解决方案1】:

    我认为您可能需要添加 findViewById 或类似的东西


    编辑:根据我的评论,以上内容不正确正确答案是

    setTextColor(getResources().getColorStateList(R.color.redeemlist_item_color));
    

    【讨论】:

    • 这是我来自 HD_Mouse 的评论:好的,也许我遗漏了太多代码。我已经调用了 findViewById()。我的问题不是空指针异常或任何东西,视图加载正常。这是 BaseAdapter 的子类中的代码。
    • 让我改写一下:您需要将 R. 转换为值。我认为正确的功能是 getViewbyid。我错了……试试这个:setTextColor(getResources().getColor(R.color.redeemlist_item_color));
    • @Rasman :这是不正确的,应该使用 setTextColor ( getResources ().getColorStateList ( R.color.redeemlist_item_color ) );
    • 但是 getResourse() 方法没有进入 ListView 的 CustomAdapter
    • @Vikky - 听起来您需要将上下文传递给您的列表视图适配器,然后您可以执行android:textColor="@drawable/selector_listview_text"
    【解决方案2】:

    你必须使用getColorStateList()

    我也在为这个问题苦苦挣扎,如果你想使用state list,你需要在color资源文件夹中声明它,而不是drawable文件夹,并使用setTextColor(getResources().getColorStateList(R.color.redeemlist_item_color))

    【讨论】:

    • 参见stackoverflow.com/questions/15543186/… 以编程方式设置 ColorStateList。
    • Resources#getColorStateList(int) 在 API 级别 23 中已弃用。请改用 Resources#getColorStateList(int, Theme)ContextCompat.getColorStateList(Context, int)
    【解决方案3】:

    你可以试试:

    holder.label.setTextColor(getResources().getColor(R.color.redeemlist_item_color));

    而不是:

    holder.label.setTextColor(R.color.redeemlist_item_color);

    【讨论】:

    • 这是不正确的,你应该使用 getColorStateList 方法而不是 getColor
    【解决方案4】:

    拉斯曼是正确的。你需要给 TextView 一个 ID,android:id="@+/something"。您可以使用该 ID 和 findViewById 检索对该特定内容的引用,然后您可以设置文本颜色。

    【讨论】:

    • 好吧,也许我遗漏了太多代码。我已经调用了 findViewById()。我的问题不是空指针异常或任何东西,视图加载正常。这是 BaseAdapter 的子类中的代码。
    猜你喜欢
    • 2016-01-08
    • 2023-04-05
    • 2015-09-20
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多