随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)、QQ技术交流群(183198395)。
Android程序国际化实际上是以Java程序国际化为基础的,而且比Java程序国际化更方便,因为Android本身就采用了XML资源文件来管理所有字符串消息,只要为各消息提供不同语言、国家对应内容即可。即开发者需要为values目录添加几个不同语言国家的版本。
values目录文件命名方式:values-语言代码-r 国家代码 示例:values-zh-rCN values-en-rUS
然后在这个两个目录下分别创建资源文件如strings.xml,显然在values-zh-rCN目录下的strings.xml就是简体中文的字符串资源文件;在values-en-rUS下的strings.xml就是美式英语的字符串资源文件。
下面用一个实例来演示国际化Android的应用:
Activity:
package com.lovo.activity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText show = (EditText) findViewById(R.id.main_et1);
// 设置文本框所显示的文本
show.setText(R.string.msg);
}
}
布局XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/main_et1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:editable="false"
android:gravity="top"
android:lines="2" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<!-- 两个按钮的文本都是通过消息资源指定的 -->
<Button
android:id="@+id/main_btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ok" />
<Button
android:id="@+id/main_btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel" />
</LinearLayout>
</LinearLayout>
values-en-rUS目录下的Strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="ok">OK</string>
<string name="cancel">Cancel</string>
<string name="msg">Hello!</string>
</resources>
values-zh-rCN目录下的Strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="ok">确定</string>
<string name="cancel">取消</string>
<string name="msg">你好!</string>
</resources>