在Android中新建一个项目
在value目录下,右键New->Value resource file:
命名为strings.xml,因为本身存在一个英文下的strings.xml文件,以下选择中文,点击locale右边的箭头
然后选择语言
中英文下的strings.xml创建好了。
定义几个字符串以作测试:
<resources>
<string name="app_name">Demo1</string>
<string name="content">LanguageTest</string>
<string name="btn_next">Next Page</string>
<string name="content2">This is page two</string>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Demo1</string>
<string name="content">语言测试</string>
<string name="btn_next">下一页</string>
<string name="content2">这是第二页</string>
</resources>
默认的string.xml,否则在新建string.xml文件后设置字符串的值会报错。
两个文件下的string需要同步编写,即不同语言的字符串资源的名称要一样。
至此,若在使用@string/变量名为变量设置文本时,APP的语言也会随系统语言而改变。
如想在代码中改变APP的语言,可在第一个Activity中添加如下代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Resources resources = getResources();//获得res资源对象
Configuration config = resources.getConfiguration();//获得设置对象
DisplayMetrics dm = resources .getDisplayMetrics();//获得屏幕参数:主要是分辨率,像素等。
config.locale = Locale.SIMPLIFIED_CHINESE; //简体中文
//config.locale=Locale.ENGLISH;//英语
resources.updateConfiguration(config, dm);
setContentView(R.layout.activity_main);
}
通过以上代码,可以手动设置APP的语言