如何支持多种设备-语言篇

来源:互联网 发布:mac怎么卸载 编辑:程序博客网 时间:2024/06/07 14:00

android设备种类繁多,包括各种各样的形状与尺寸,所以一个优秀的android app应该能够适用各种android设备。

1、支持不同的语言

将界面上显示的字符串从代码中提取出来,放在一个专门的文件中保存是一个非常好的主意。android把它保存在res/values/strings.xml中。

针对不同的语言,我们可以在res/文件夹下面创建各个语言版本的子values文件夹来保存相应的语言,子文件夹命名规则为values-语言种别code。如下面所示

MyProject/    res/       values/           strings.xml       values-es/           strings.xml       values-fr/           strings.xml
res/values/strings.xml中保存的是英语,res/values-es/strings.xml中保存的是西班牙语,res/values-fr/strings.xml中保存的是法语。

English (default locale), /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>

Spanish, /values-es/strings.xml:

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="title">Mi Aplicación</string>    <string name="hello_world">Hola Mundo!</string></resources>

French, /values-fr/strings.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资源如何使用,我们就如何使用,不需要我们判断该如何使用哪种语言,因为在程序运行的时候,android系统会根据当前机器语言环境,自动选择对应的string.xml。

For Example:

java code中:

// Get a string resource from your app's ResourcesString hello = getResources().getString(R.string.hello_world);// Or supply a string resource to a method that requires a stringTextView textView = new TextView(this);textView.setText(R.string.hello_world);

xml code中:

<TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="@string/hello_world" />


0 0
原创粉丝点击