Rus*_*art 6 android textcolor textview
我有简单文本项的列表视图.这些项目中的TextView看起来像这样(它包含在一个内部RelativeLayout):
<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" />
Run Code Online (Sandbox Code Playgroud)
我想为文本使用以下颜色状态选择器,我称之为"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>
Run Code Online (Sandbox Code Playgroud)
通常,当然,我可以将其设置android:textColor为xml中的属性,但在这种情况下,我需要使用此选择器("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>
Run Code Online (Sandbox Code Playgroud)
所以我在适配器中设置文本颜色(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);
}
Run Code Online (Sandbox Code Playgroud)
除了一个问题外,这个工作正常:单击项目时文本颜色不会改变.即使我立即调用setDuplicateParentStateEnabled(true)该项目setTextColor(),该设置也完全被忽略.
我通过注释掉设置文本颜色的Java代码并在xml中设置它来测试这个,并且选择器工作得很好.但是如果我以编程方式设置textColor,它完全无法复制父状态.
谁看过这个吗?有没有解决方法,或者这只是我必须忍受的Android错误?
Rus*_*art 22
好的,发现我的错误.我应该用getResources().getColorStateList()而不是getResources().getColor().将此留给任何犯同样错误的人.
| 归档时间: |
|
| 查看次数: |
23773 次 |
| 最近记录: |