格式化字符串

格式化字符串示例

在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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值