我有一个over-flow菜单,从中单击语言可以获得单选项(语言列表)。我已经写了这个代码
AlertDialog.Builder languageDialog = new AlertDialog.Builder(
MainActivity.this);
languageDialog.setTitle(R.string.chooseLanguage);
final String[] languageOptions = { "English", "Nepali" };
languageDialog.setSingleChoiceItems(languageOptions, 0,
new DialogInterface.OnClickListener() {
@SuppressLint("NewApi")
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
setLanguage("es");
} else if (which == 1) {
setLanguage("ne");
}
dialog.dismiss();
}
});
languageDialog.show();
for list of Dailog and
@SuppressLint("NewApi")
private void setLanguage(String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
android.content.res.Configuration config = new Configuration();
config.locale = locale;
this.getResources().updateConfiguration(config,
this.getResources().getDisplayMetrics());
MainActivity.this.recreate();
} method to set locale
问题是,在屏幕方向改变后,语言又变回了设备语言,为什么?我缺了什么吗?我在阅读时对小行星清单文件进行了更改,但没有任何解决方案对我有效。有什么帮助吗?
在特定活动的AnroidMenifest.xml文件中添加以下行。
android:configChanges="orientation|layoutDirection|screenSize"
是的,不幸的是,Android不喜欢更改语言。要使其工作,您需要在onCreate之前在EACH活动中调用setLanguage方法。
changing orientation destroy activity and **recreate** it so when it **recreated** it changes to language that set in **oncreate** method.you have to save value in **saveinstatestate** and check on **oncreate** method
if(saveinstatntate!=null)`enter code here`
{
//then set the saved language
}
else
{
//defaultvalue
}
我认为,你应该在你的Android清单文件中添加:
android:configChanges="locale|orientation"
在你的课上,你应该有这些导入:
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;
本地化代码应该是这样的:
public void setLocale(String lang)
{
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, AndroidLocalize.class);
startActivity(refresh);
finish();
}
请阅读:当用户选择语言时,如何更改应用程序的语言?
另请阅读:
在Android 中以编程方式更改语言
在Android首选项中设置应用程序语言