android 中使用i18n 资源
访问量: 2838
参考: https://developer.android.com/training/basics/supporting-devices/languages.html
使用国际化,需要做的是:
1. 知道如何使用 i18n 字符串, (知道如何带参数使用)
2. 知道如何动态的切换locale
如何使用i18n字符串?
1. 保证 app/src/main 目录下的 res 有两个目录: (新建一个values-b+zh 目录)
res/values/strings.xml 这个是默认的文件夹和文件 所以,文件夹名字就是 res/values
res/values-b+zh/strings.xml 这个是中文字符。
<resources>
<string name="switch_language_button">切换语言</string>
</resources>
2. 保证 res/values-b+zh 目录下,的 strings.xml 文件有内容。 (例如都写成中文)
例如:
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/switch_language_button" android:textAllCaps="false" (记得加上这句,否则按钮会默认都是英文大写,我服了) />
就可以了。
3. 运行 (shift + f10),就可以看到效果了。(会显示默认的语言, 这个默认的语言是由当前手机的 Locale 决定的(在android - 设置中))
4. 我们也可以“静态的”让android 强制显示某种语言。
在对应的activity 中,加入下面的代码,(以我的activity 为例子)
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String languageToLoad = "en"; // 修改这里成为 zh 就是中文, en 就是英文(默认的) Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration configuration = new Configuration(); configuration.locale = locale; getBaseContext().getResources().updateConfiguration( configuration, getBaseContext().getResources().getDisplayMetrics() ); this.setContentView(R.layout.activity_main); }