如转载请注明出处http://blog.youkuaiyun.com/ethanchiu/article/details/19542401
支持不同的语言
将UI的strings从app代码中提取出来,并把他们放到一个外部文件中,这是一个好的方式。android通过一个项目中的资源文件使得这些很容易做到。在项目的顶层有个res/目录,在这个目录里有很多子目录。有些默认的文件比如res/values/strings.xml,它保存了你的string值。
创建本地目录和String文件
为了支持更多的语言,创建额外的values目录,这个values目录的名字后面跟着连字符和国家iso编码代号。比如,values-es/这个目录包含的资源是提供给为本地语言为“es”的资源。android会根据设备运行时的本地设置读取合适的资源。一旦你决定了你要支持的语言,创建子目录和string资源文件。比如
MyProject/
res/
values/
strings.xml
values-es/
strings.xml
values-fr/
strings.xml
将string值放到恰当的文件中。
在运行的时候,android系统使用合适的string资源设置是基于当前用户的本地设置。
比如,下面是不同语言对应不同的string资源。
英语(默认的本地设置),/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="title">My Application</string>
<string name="hello_world">Hello World!</string>
</resources>
西班牙语,/values-es/string.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="title">Mi Aplicación</string>
<string name="hello_world">Hola Mundo!</string>
</resources>
法语,/values-fr/string.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="title">Mon Application</string>
<string name="hello_world">Bonjour le monde !</string>
</resources>
使用String资源
可以在代码和xml文件中通过<string>元素中的name属性定义的资源名字引用string资源。
在代码中,可以使用R.string.<string_name>这个语法引用string资源。有很多访问string资源的方式。
比如:
// Get a string resource from your app's Resources
String hello = getResources().getString(R.string.hello_world);
// Or supply a string resource to a method that requires a string
TextView textView = new TextView(this);
textView.setText(R.string.hello_world);
在xml文件中,可以通过@string/<string_name>语法引用string资源
比如:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />