string.xml字符串的格式化和样式(Formatting and Styling)
string.xml是一个字符串资源,为程序提供了可格式化和可选样式的字符串。
一般的字符串定义:
<stringname="hello_kitty">Hellokitty</string>
资源引用
在xml中:@string/hello_kitty
在java中:R.string.hello_kitty
一、当字符串有引号时
<stringname="good_example">"This'llwork"</string><stringname="good_example_2">This\'llalsowork</string><stringname="bad_example">Thisdoesn'twork</string><stringname="bad_example_2">XMLencodingsdon'twork</string>
如果字符串中有单引号,则要将整个字符串用双引号包起来,或者使用转义\'
二、当字符串需要用String.format格式化时
<stringname="hello_kitty">Hello%1$skitty</string>
%1$s : 1表示占第一位,s表示字符串,d表示数字
java代码:
Stringformat=String.format(R.string.hello_kitty,"your");
三、当字符串有html标记时
<b>kitty</b> 加粗
<stringname="hello_kitty">Hello<b>kitty</b></string>
java代码:
Resourcesres=getResources();Stringkitty=res.getString(R.string.hello_kitty);//textView.setText(kitty);
四、当字符串又需要格式化,又有样式的时候
<stringname="hello_kitty"><i>Hello</i><b>%1$skitty</b>!</string>
上面是错误的写法,因为参考原文一段话
In this formatted string, a<b>
element is added. Notice that the opening bracket is HTML-escaped, using the<
notation.
所以我们需要这么写
<stringname="hello_kitty"><i>Hello</i><b>%1$skitty</b>!</string>
java代码:
Stringformat=String.format(res.getString(R.string.hello_kitty),"your");Spannedhtml=Html.fromHtml(format);textView.setText(html);
Html.fromHtml()会解析所有html标记,但如果String.format()的参数中有html标记但又不想被Html解析
比如 <u>your</u>,就要对参数进行编码
java代码:
Resourcesres=getResources();Stringencode=TextUtils.htmlEncode("<u>your</u>");Stringformat=String.format(res.getString(R.string.hello_kitty),encode);Spannedhtml=Html.fromHtml(format);tv1.setText(html);
tip:
Spannedhtml=Html.fromHtml(format);StringhtmlStr=Html.fromHtml(format).toString();//有样式tv1.setText(html);//无样式tv2.setText(htmlStr);
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。