我想更改应用程序的语言环境(语言),以便当用户希望使用“更改语言”按钮在北印度语和英语之间切换时进行编程更改。
我有一个代码来更改语言,但是仅当我在setContentView()方法之前在活动的onCreate()中调用时它才起作用。
任何帮助深表感谢。
在这里看到我的答案
例如,如果您希望您的应用程序同时支持英语和阿拉伯语字符串(除了默认字符串),则可以简单地创建两个其他资源目录,分别称为/res/values-en(对于英语strings.xml)和
/res/values-ar(对于阿拉伯语strings.xml)。
在strings.xml文件中,资源名称相同。
例如,/res/values-en/strings.xml文件可能如下所示:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello in English!</string>
</resources>
Run Code Online (Sandbox Code Playgroud)
而/res/values-ar/strings.xml文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">????? ?? ????? ??????????</string>
</resources>
Run Code Online (Sandbox Code Playgroud)
同样,对于urdu来说,/res/values-ur_IN/strings.xml文件看起来像这样:
印度的ur_IN巴基斯坦的ur_PK
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">??????? ??? ???!!</string>
</resources>
Run Code Online (Sandbox Code Playgroud)
/ res / layout目录中显示字符串的默认布局文件通过变量名@ string / hello引用该字符串,而不考虑字符串资源所使用的语言或目录。
Android操作系统确定在运行时加载哪个版本的字符串(法语,英语或默认)。带有TextView控件以显示字符串的布局可能如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/hello" >
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
可以通过常规方式以编程方式访问该字符串:
String str = getString(R.string.hello);
Run Code Online (Sandbox Code Playgroud)
要更改语言,您需要喜欢该更改语言。
btn_english.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(this, getResources().getString(R.string.lbl_langSelectEnglis), Toast.LENGTH_SHORT).show();
}
});
btn_arbice.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Locale locale = new Locale("ar");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(this, getResources().getString(R.string.lbl_langSelecURdu), Toast.LENGTH_SHORT).show();
}
});
btn_urdu.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Locale locale = new Locale("ur_IN");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(HomeActivity.this, getResources().getString(R.string.lbl_langSelectEnglis), Toast.LENGTH_SHORT).show();
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4289 次 |
| 最近记录: |