格式化字符串示例
在strings.xml文件中定義:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
Java代碼:
TextView textView = (TextView) findViewById(R.id.text);
textView.setText(String.format(getResources().getString(R.string.welcome_messages), "LiLei", 1));
關於string
下面是官方給出的正確/錯誤的例子:
下面是官方給出的正確/錯誤的例子:
//不使用轉義符則需要用雙引號包住整個string
<string name="good_example">"This'll work"</string>
//使用轉義符
<string name="good_example_2">This\'ll also work</string>
//錯誤
<string name="bad_example">This won't work!</string>
//錯誤 不可使用html轉義字符
<string name="bad_example_2">XML encodings won't work either!</string>
對於帶格式的string,例如在字符串中某些文字設置顏色,可以使用html標簽。對於這類型的string,需要進行某些處理,在xml里面不可以被其他資源引用。官方給了一個例子來對比普通string和帶格式string的使用:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="simple_welcome_message">Welcome!</string> <string name="styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string> </resources>
Xml代碼:
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAlign="center" android:text="@string/simple_welcome_message"
/>
Java代碼:
// Assign a styled string resource to a TextView on the current screen. CharSequence str = getString(R.string.styled_welcome_message); TextView tv = (TextView)findViewByID(R.id.text); tv.setText(str);
另外對於帶風格/格式的string的處理,就麻煩一點點。官方給了一個例子:
這里的%1$d是個十進制數字,%2$s是字符串。當我們把某個字符串賦值給%2$s之前,需要用htmlEncode(String)函數處理那個字符串:
然后用String.format() 來實現賦值,接着用fromHtml(String) 得到格式化后的string:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="search_results_resultsTextFormat">%1$d results for <b>&quot;%2$s&quot;</b></string> </resources>
//title是我們想賦值給%2$s的字符串 String escapedTitle = TextUtil.htmlEncode(title);
String resultsTextFormat = getContext().getResources().getString(R.string.search_results_resultsTextFormat); String resultsText = String.format(resultsTextFormat, count, escapedTitle); CharSequence styledResults = Html.fromHtml(resultsText);