我有简单文本项目的列表视图。这些项目中的TextView中看起来是这样的(它的一个包裹里面RelativeLayout
):使用setTextColor()以编程方式设置Android TextView文本颜色呈现android:duplicateParentState无效
<TextView
android:id="@+id/text_language_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:duplicateParentState="true"
android:textSize="16sp"
android:textStyle="bold" />
我想使用的文本,这是我所谓的“dark_list_text_states.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="@android:color/white"/>
<item android:color="@color/dark_list_text"/>
</selector>
当然,我可以将它设置为xml中的android:textColor
属性,但在这种情况下,我需要使用此选择器(“blue_text_states.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="@android:color/white"/>
<item android:color="@color/selected_blue"/>
</selector>
所以我设置文本颜色的适配器(language_name
和selected
在代码前面定义):
TextView text_language_name = (TextView)view.findViewById(R.id.text_language_name);
if (text_language_name != null) {
text_language_name.setText(language_name);
int text_color = selected
? getResources().getColor(R.color.blue_text_states)
: getResources().getColor(R.color.dark_list_text_states);
text_language_name.setTextColor(text_color);
text_language_name.setDuplicateParentStateEnabled(true);
}
这工作正常,但有一个问题:文本颜色没有变化时,项目被点击。尽管我在setTextColor()
之后立即致电setDuplicateParentStateEnabled(true)
,但该设置完全被忽略。
我已经通过评论设置文本颜色并将其设置在xml中的Java代码进行了注释测试,选择器工作得很好。但是,如果我以编程方式设置textColor,则完全无法复制父状态。
有没有人见过这个?有没有解决方法,或者这只是一个我必须忍受的Android错误?
接受这个作为答案。它的帮助。 –
谢谢你提醒我。完成。 –