打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
string标签

android developers上说的,string resource 不仅能定义字符串,还支持字符串的styling和formatting。

android 通过如下方法来定义字符串资源

字符串


  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string  
  4.         name="string_name"  
  5.         >text_string</string>  
  6. </resources>  

name 属性为该string的id。可通过 Activity的getString(id)的方法在代码中获得字符串的值。

字符串数组

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string-array  
  4.         name="string_array_name">  
  5.         <item  
  6.             >text_string</item>  
  7.     </string-array>  
  8. </resources>  

在代码里面可以这样获得字符串数组资源
  1. Resources res = getResources();  
  2. String[] planets = res.getStringArray(R.array.planets_array);  

字符串格式化
在字符串中出现单引号和双引号,不能直接写于xml中:
  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't work</string>  

在资源中定义的字符串同样支持格式化.
  1. <string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>  
  2. Resources res = getResources();  
  3. String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);  

使用HTML标签
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="welcome">Welcome to <b>Android</b>!</string>  
  4. </resources>  
  5. <TextView  
  6.     android:layout_width="fill_parent"  
  7.     android:layout_height="wrap_content"  
  8.     android:text="@string/welcome" />  

这样在TextView中”Android”会显示为粗体.

在代码中可以这样使用:

  1. Resources res = getResources();  
  2. String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);  
  3. CharSequence styledText = Html.fromHtml(text);  

在文档中说支持的html标签,只有:
  1. <b>  
  2. <i>  
  3. <u>  

但是,Html.fromHtml(text)支持的html标签却不只这些,具体有那些android平台并没有详细列举.在 HTML Tags Supported By TextView 有详细列举.但是额外的标签不能直接定义在xml中.貌似会被过滤掉.所以使用额外的标签时,必须用<![CDATA[ xx ]]>包围住.当然这样的字符串就不能直接在xml中调用了.只能通过代码使用.
  1. <string name="welcome_info_2">        <![CDATA[  
  2.         欢迎你,<font color="#c5663e">%s</font>  
  3.         ]]>  
  4.     </string>  
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
android获取string.xml的值
android应用程序结构
Android 中的资源访问
修改Android中strings.xml文件, 动态改变数据
Android string.xml中使用html标签
C# 如何将一个字符串转换成字节数组”与“如何将一个字节数组转换成一个字符串
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服