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);