温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-06-27 18:46:18 来源:网络 阅读:2318 作者:孙伯符 栏目:开发技术

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); 

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

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); 

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

 

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI