以编程方式将TextView颜色设置为<selector>

38

我在res/color/redeemlist_item_color.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。 当我在XML上设置此TextViewandroid:textColor为上面的选择器时,当选中该项时,颜色正确更改。 但是,我正在尝试以以下方式编程方式设置此资源:

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

当以这种方式设置时,颜色不再改变。是否可以使用选择器以这种方式分配给TextView

5个回答

69

我认为你可能需要添加findViewById或类似的内容。


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

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

这是我在HD_Mouse的评论:好的,也许我省略了太多代码。我已经调用了findViewById()。我的问题不是空指针异常或其他任何问题,视图加载得很好。这段代码位于BaseAdapter的子类中。 - Neil Goodman
2
让我重新表述一下:你需要将R转换为一个值。我以为正确的函数是getViewbyid。我错了...试试这个:setTextColor(getResources().getColor(R.color.redeemlist_item_color)); - Rasman
27
@Rasman:“这不正确,应该使用 **setTextColor(getResources().getColorStateList(R.color.redeemlist_item_color));**。” - Leeeeeeelo
但是在ListView的CustomAdapter中,getResourse()方法没有被调用。 - Vikky
@Vikky - 听起来你需要将上下文传递给你的ListView适配器,然后你就可以使用android:textColor="@drawable/selector_listview_text"了。 - Someone Somewhere
Resources#getColorStateList(int)在API 23中已被弃用。请改用Resources#getColorStateList(int, Theme)ContextCompat.getColorStateList(Context, int) - Christian García

42

您需要使用 getColorStateList() 方法。

我也曾经遇到过这个问题,如果你想使用一个状态列表,你需要在 color 资源文件夹中声明它,而不是在 drawable 文件夹中,并使用 setTextColor(getResources().getColorStateList(R.color.redeemlist_item_color)) 方法。


请参考 https://dev59.com/UGUp5IYBdhLWcg3wEEXd 了解如何以编程方式设置 ColorStateList。 - Rock Lee
Resources#getColorStateList(int)在API 23中已被弃用。请改用Resources#getColorStateList(int, Theme)ContextCompat.getColorStateList(Context, int) - Christian García

4
您可以尝试以下代码替换原有代码:
holder.label.setTextColor(getResources().getColor(R.color.redeemlist_item_color));
原有代码为:
holder.label.setTextColor(R.color.redeemlist_item_color);
这样做能够使代码更加通俗易懂。请注意,HTML标签已被保留。

这不正确,应该使用getColorStateList方法而不是getColor - Leeeeeeelo

0
Rasman是正确的。您需要为TextView提供一个ID,android:id="@+/something"。您可以使用该ID和findViewById检索对该特定对象的引用,然后可以设置文本颜色。

好的,也许我省略了太多代码。我已经调用了findViewById()。我的问题不是空指针异常或其他任何问题,视图加载得很好。这段代码位于BaseAdapter的子类中。 - Neil Goodman

0
Can use 

context.getColorStateList(colorSelectorId) // if your app minAPI level >= 23
// or 
ContextCompat.getColorStateList(context, colorSelectorId) // for any API


because resources.getColorStateList(id) deprecated: @deprecated Use {@link #getColorStateList(int, Theme)} instead.

示例
textView.setTextColor(context.getColorStateList(R.color.text_color_selector))
textView.setTextColor(ContextCompat.getColorStateList(context, R.color.text_color_selector))

我更喜欢使用ContextCompat.getColorStateList,因为它适用于所有的API。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接