Android资源的使用之String
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>
<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);
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表示繁体中文。
进入“设置”程序,选择“区域和文本”,可以选择对应的语言测试。