每当用户从微调器中选择一个时,我都需要保存应用的区域设置。现在我可以更改它,但如果用户退出应用程序,则需要保存会话。
继承我的代码:
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getActivity().getBaseContext().getResources().updateConfiguration(config,
getActivity().getBaseContext().getResources().getDisplayMetrics());
SharedPreferences shp = getActivity().getSharedPreferences(
"android.exaple.com.PREFERENCES", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shp.edit();
editor.putString("USER_LANGUAGE", lang);
editor.apply();
答案 0 :(得分:0)
好的,让我们给你举个例子,好吧我会在这种情况下使用Aleart Dialog,你可以用微调器来试试。
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.chooselanguage).setItems(R.array.language, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0:
SharedPreferences ensharedPreferences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
SharedPreferences.Editor eneditor = ensharedPreferences.edit();
eneditor.putString("language", "en");
eneditor.commit();
Toast.makeText(MainActivity.this, "English Selected", Toast.LENGTH_SHORT).show();
break;
case 1:
SharedPreferences npsharedPrefrences = getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
SharedPreferences.Editor npeditor = npsharedPrefrences.edit();
npeditor.putString("language", "ne");
npeditor.commit();
Toast.makeText(MainActivity.this, "Nepali Selected", Toast.LENGTH_SHORT).show();
}
}
}).setCancelable(false).create().show();
现在,该语言将根据顶级代码的选择进行保存。现在使用以下代码在您的活动的onStart()回调中调用它们。
SharedPreferences sharedPreferences = this.getSharedPreferences("selectedLanguage", Context.MODE_PRIVATE);
String pine = sharedPreferences.getString("language", DEFAULT);
String languageToLoad = pine;
Locale locale = new Locale(languageToLoad);//Set Selected Locale
Locale.setDefault(locale);//set new locale as default
Configuration config = new Configuration();//get Configuration
config.locale = locale;//set config locale as selected locale
this.getResources().updateConfiguration(config, this.getResources().getDisplayMetrics());
你可能也会遇到这样的问题:如果用户选择的语言为尼泊尔语但仍然显示英语,并且只需要重新启动应用程序,那么你需要在微调器中添加以下代码。
Intent intent=getIntent();
overridePendingTransition(0, 0);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
以上代码将重启当前活动。而那个overridePendingTransition(0,0);在打开和关闭活动时删除过渡动画。希望这有帮助!!