格式化字符串示例

来源:互联网 发布:md编辑器 mac 编辑:程序博客网 时间:2024/05/17 07:16

格式化字符串示例

在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&apos;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的处理,就麻烦一点点。官方给了一个例子:
<?xml version="1.0" encoding="utf-8"?> <resources>   <string name="search_results_resultsTextFormat">%1$d results for &lt;b>&amp;quot;%2$s&amp;quot;&lt;/b></string> </resources> 
这里的%1$d是个十进制数字,%2$s是字符串。当我们把某个字符串赋值给%2$s之前,需要用htmlEncode(String)函数处理那个字符串:
//title是我们想赋值给%2$s的字符串 String escapedTitle = TextUtil.htmlEncode(title); 
然后用String.format() 来实现赋值,接着用fromHtml(String) 得到格式化后的string:
String resultsTextFormat = getContext().getResources().getString(R.string.search_results_resultsTextFormat); String resultsText = String.format(resultsTextFormat, count, escapedTitle); CharSequence styledResults = Html.fromHtml(resultsText); 
0 0