如何以编程方式更改语言? [英] How to programmatically change language?
本文介绍了如何以编程方式更改语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想以编程方式更改语言.
I want to programmatically change the language.
所以我建立了两个xml文件.
So I have built two xml files.
values-it
-->string.xml
values-en
-->string.xml
这是MainActivity中用于更改整个应用程序语言的代码:
This is the code in MainActivity to change the language of the whole application:
//意大利语
Resources res = getApplicationContext().getResources();
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = new Locale("it");
res.updateConfiguration(conf, dm);
//英语
Resources res2 = getApplicationContext().getResources();
DisplayMetrics dm2 = res2.getDisplayMetrics();
android.content.res.Configuration conf2 = res2.getConfiguration();
conf2.locale = new Locale("en");
res2.updateConfiguration(conf2, dm2);
现在,如果我设置了英语(例如),则代码会正确执行,但标签不会更改其文本.
如果我更改设备的方向,则标签会正确更改其文本.
Now if I set the English language (for example) the code is executed with no error, but the label doesn't not change its text.
If I change the orientation of my device, the label changes its text correctly.
现在如何修改代码以自动刷新标签?
Now how can I modify my code to automatically refresh the label?
推荐答案
AlertDialog.Builder builder = new AlertDialog.Builder(DashboardActivity.this);
builder.setTitle(R.string.languages);
// Add the buttons
builder.setPositiveButton(R.string.english, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String languageToLoad = "en"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
dialog.dismiss();
rEditor.putString("language", languageToLoad);
rEditor.commit();
Intent refresh = new Intent(DashboardActivity.this, DashboardActivity.class);
startActivity(refresh);
finish();
}
});
builder.setNegativeButton(R.string.gujarati, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
String languageToLoad = "gu"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
dialog.dismiss();
rEditor.putString("language", languageToLoad);
rEditor.commit();
Intent refresh = new Intent(DashboardActivity.this, DashboardActivity.class);
startActivity(refresh);
finish();
}
});
builder.create().show();
您必须重新加载活动才能显示新的语言文本,这意味着重新启动.
you have to reload activity to show new language text means restart.
这篇关于如何以编程方式更改语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文