string.xml是一个字符串资源,为程序提供了可格式化和可选样式的字符串。html
通常的字符串定义:java
- <string name="hello_kitty">Hello kitty</string>
资源引用ide
在xml中:@string/hello_kittythis
在java中:R.string.hello_kitty编码
1、当字符串有引号时spa
<b><
- <string name="good_example">"This'll work"</string>
- <string name="good_example_2">This\'ll also work</string>
- <string name="bad_example">This doesn't work</string>
- <string name="bad_example_2">XML encodings don't work</string>
若是字符串中有单引号,则要将整个字符串用双引号包起来,或者使用转义\'code
2、当字符串须要用String.format格式化时orm
- <string name="hello_kitty">Hello %1$s kitty</string>
%1$s : 1表示占第一位,s表示字符串,d表示数字xml
java代码:htm
- String format=String.format(R.string.hello_kitty,"your");
3、当字符串有html标记时
<b>kitty</b> 加粗
- <string name="hello_kitty">Hello <b>kitty</b></string>
java代码:
- Resources res = getResources();
- String kitty = res.getString(R.string.hello_kitty);
- //textView.setText(kitty);
4、当字符串又须要格式化,又有样式的时候
- <string name="hello_kitty"><i>Hello</i><b> %1$s kitty</b>!</string>
上面是错误的写法,由于参考原文一段话
In this formatted string, a element is added. Notice that the opening bracket is HTML-escaped, using the notation.
因此咱们须要这么写
- <string name="hello_kitty"><i>Hello</i><b> %1$s kitty</b>!</string>
java代码:
- String format = String.format(res.getString(R.string.hello_kitty),
- "your");
- Spanned html = Html.fromHtml(format);
- textView.setText(html);
Html.fromHtml()会解析全部html标记,但若是String.format()的参数中有html标记但又不想被Html解析
好比 <u>your</u>,就要对参数进行编码
java代码:
- Resources res = getResources();
- String encode = TextUtils.htmlEncode("<u>your</u>");
- String format = String.format(res.getString(R.string.hello_kitty),
- encode);
- Spanned html = Html.fromHtml(format);
- tv1.setText(html);
tip:
- Spanned html = Html.fromHtml(format);
- String htmlStr = Html.fromHtml(format).toString();
- //有样式
- tv1.setText(html);
- //无样式
- tv2.setText(htmlStr);