在设置了textview属性的颜色之后,这个提示符在运行时会出现在logcat上,这意味着什么?
当将文本视图颜色还原为默认颜色时,错误消失,一切正常运行。
怎么回事?如何正确设置文本视图的颜色?谢谢,
11-11 00:45:56.302: E/TextView(2828): Saved cursor position 2/2 out of range for (restored) text
我忘了我在程序中更改了什么,在logcat中有提示符,
enter code here
11-11 01:40:48.102: E/AndroidRuntime(2921): Caused by: android.content.res.Resources$NotFoundException: File #ff0000 from drawable resource ID #0x7f050018: .xml extension required
11-11 01:40:48.102: E/AndroidRuntime(2921): at android.content.res.Resources.loadColorStateList(Resources.java:2255)
11-11 01:40:48.102: E/AndroidRuntime(2921): at android.content.res.TypedArray.getColorStateList(TypedArray.java:342)
11-11 01:40:48.102: E/AndroidRuntime(2921): at android.widget.TextView.<init>(TextView.java:956)
11-11 01:40:48.102: E/AndroidRuntime(2921): at android.widget.TextView.<init>(TextView.java:614)
11-11 01:40:48.102: E/AndroidRuntime(2921): ... 27 more
11-11 01:40:53.693: I/Process(2921): Sending signal. PID: 2921 SIG: 9
在布局中,我设置
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
...
android:textColor="@string/TColor" />
在string.xml中,
<string name="TColor">#ff0000</string>
发布于 2013-12-03 03:41:04
您需要将#ff0000存储为颜色而不是字符串。
将颜色放在项目的res/values文件夹中的colors.xml文件中。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="my_color>#ff0000</color>
</resources>
然后在文本视图中使用:
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
...
android:textColor="@color/my_color" />
<Additional>
读了你最后的评论,我想我知道你在哪里困惑了。
是的,您可以将不同的资源类型放在一个XML文件中。但它们仍然必须被宣布为正确的类型。例如,下面的第一个XML很好:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="t_color">#ff0000</color>
<color name="t_color_alternate">#dd0011</color>
<string name="text_1">First Text</string>
<string name="text_2">Second Text</string>
<color name="another_color">#ee3311</color>
<dimen name="my_margin">16dp</dimen>
<string name="text_3">Third Text</string>
</resources>
但是,当您尝试使用资源时,由于类型不正确,第二个XML将导致问题:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="t_color">16dp</color>
<color name="t_color_alternate">Fred</color>
<color name="another_color">Rectangle</color>
<dimen name="my_margin">Blue</dimen>
</resources>
<Second Additional>
当您声明<string name="TColor">#ff0000</string>
时,编译器将创建一个String对象,并在运行应用程序时使用"#ff0000“字符填充它。
换句话说,这就像用代码编写String TColor = "#ff0000"
。
同样,当您声明<color name="TColor">#ff0000</color>
时,编译器将创建一个颜色对象,并在运行应用程序时填充它的颜色#ff0000。
这就像用代码编写Color TColor = 0xff0000
一样。
如果您阅读String的参考文档,您将看到它表示一个字符序列。另一方面,颜色表示整数的序列。
最后,如果您阅读TextView
,您将看到XML属性android:textColor
与方法setTextColor(int)
等效。因此,当您编写<string name="TColor">#ff0000</string>
时,您正在尝试将字符串放入setTextColor(int)
。
https://stackoverflow.com/questions/20341103
复制相似问题