Android资源的使用之String

[url]http://www.cnblogs.com/dawei/archive/2010/04/26/1721525.html[/url]

Android允许定义多个字符串资源文件在res/values 中
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World!</string>
<string name="app_name">App Name</string>
</resources>

当在此创建或修改资源文件时,ADT都会自动更新R.java ,并产生唯一的标识符来标识,如:
public static final class string {
public static final int app_name=0x7f040004;
public static final int hello=0x7f040003;
}

在程序中使用资源就可以用R.string.hello来标识字符串了,并可用Activity中的getText(R.string.hello)直接转成字符串
特殊格式字符串
代码
<resources> 
<string name="java_format_string">
hello %2$s java format string. %1$s again
</string>
<string name="tagged_string">
Hello <b><i>Slanted Android</i></b>, You are bold.
</string>
</resources>

复制代码

这里的特殊格式字符串指的是带参数的格式字符串,及带有HTML标签的字符串。
读取操作可以这样

代码
//Read a Java format string 
String javaFormatString = activity.getString(R.string.java_format_string);
//Convert the formatted string by passing in arguments
String substitutedString = String.format(javaFormatString, "Hello" , "Android")
//set the output in a text view
textView.setText(substitutedString);

//Read an html string from the resource and set it in a text view
String htmlTaggedString = activity.getString(R.string.tagged_string);
//Convert it to a text span so that it can be set in a text view
//android.text.Html class allows painting of "html" strings
//This is strictly an Android class and does not support all html tags
Spanned textSpan = android.text.Html.fromHtml(htmlTaggedString);
//Set it in a text view
textView.setText(textSpan);

复制代码


支持多国语言
要让应用程序支持多个语言界面,并不需要重新定义界面。只需要添加一个语言资源目录放置相应的字符串资源文件 如:res/values-en 表示英文字符串 ,res/values-zh-rCN表示简体中文 res/values-zh-rTW表示繁体中文。
进入“设置”程序,选择“区域和文本”,可以选择对应的语言测试。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值