string.xml字符串的格式化和樣式(Formatting and Styling)

string.xml是一個字符串資源,爲程序提供了可格式化和可選樣式的字符串。

一般的字符串定義:

  1. <string name="hello_kitty">Hello kitty</string> 

資源引用

在xml中:@string/hello_kitty

在java中:R.string.hello_kitty

一、當字符串有引號時

  1. <string name="good_example">"This'll work"</string> 
  2. <string name="good_example_2">This\'ll also work</string> 
  3. <string name="bad_example">This doesn't work</string> 
  4. <string name="bad_example_2">XML encodings don&apos;t work</string> 

如果字符串中有單引號,則要將整個字符串用雙引號包起來,或者使用轉義\'

二、當字符串需要用String.format格式化時

  1. <string name="hello_kitty">Hello %1$s kitty</string> 

%1$s : 1表示佔第一位,s表示字符串,d表示數字

java代碼:

  1. String format=String.format(R.string.hello_kitty,"your"); 

三、當字符串有html標記時

<b>kitty</b> 加粗

  1. <string name="hello_kitty">Hello <b>kitty</b></string> 

java代碼:

  1. Resources res = getResources(); 
  2. String kitty = res.getString(R.string.hello_kitty); 
  3. //textView.setText(kitty); 

四、當字符串又需要格式化,又有樣式的時候

  1. <string name="hello_kitty"><i>Hello</i><b> %1$s kitty</b>!</string> 

上面是錯誤的寫法,因爲參考原文一段話

In this formatted string, a <b> element is added. Notice that the opening bracket is HTML-escaped, using the&lt; notation.

所以我們需要這麼寫

  1. <string name="hello_kitty">&lt;i>Hello&lt;/i>&lt;b> %1$s kitty&lt;/b>!</string> 

java代碼:

  1. String format = String.format(res.getString(R.string.hello_kitty), 
  2.                 "your"); 
  3.         Spanned html = Html.fromHtml(format); 
  4. textView.setText(html); 

Html.fromHtml()會解析所有html標記,但如果String.format()的參數中有html標記但又不想被Html解析

比如 <u>your</u>,就要對參數進行編碼

java代碼:

  1. Resources res = getResources(); 
  2. String encode = TextUtils.htmlEncode("<u>your</u>"); 
  3. String format = String.format(res.getString(R.string.hello_kitty), 
  4.                 encode); 
  5. Spanned html = Html.fromHtml(format); 
  6. tv1.setText(html); 

tip:

  1. Spanned html = Html.fromHtml(format); 
  2. String htmlStr = Html.fromHtml(format).toString(); 
  3.          
  4. //有樣式 
  5. tv1.setText(html); 
  6. //無樣式 
  7. tv2.setText(htmlStr); 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章