在 SettingsActivity 中,我可以在两种语言之间进行选择,该按钮只能解决此活动中的问题,但是我无法更改其他活动的语言。 我希望当我选择一种语言时,应用重新启动并更改所有其他活动的语言 , 怎么办呢? 我尝试在所有其他活动中创建方法 loadLocalLanguage ,并在 setContentView(R.layout.activity_name); < / strong>,但这似乎不是一个好主意,它导致应用程序崩溃:
private void loadLocalLanguage(){
SettingsActivity settingsActivity = new SettingsActivity();
SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String lang = mPreferences.getString("My_Language", "");
settingsActivity.setLocal(lang);
}
这是我的 SettingActivity
public class SettingsActivity extends AppCompatActivity {
LinearLayout btnLanguage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLocal();
setContentView(R.layout.activity_settings);
btnLanguage = findViewById(R.id.btn_language);
btnLanguage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showLanguageDialoge();
}
});
}
private void showLanguageDialoge() {
final String listItems[] = {"English", "العربية"};
AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
builder.setSingleChoiceItems(listItems, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
setLocal("en");
recreate();
} else if (i == 1) {
setLocal("ar");
recreate();
}
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public void setLocal(String lang) {
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration configuration = new Configuration();
configuration.locale = locale;
getBaseContext().getResources().updateConfiguration(configuration, getBaseContext().getResources().getDisplayMetrics());
SharedPreferences.Editor editor = getSharedPreferences("settings", MODE_PRIVATE).edit();
editor.putString("My_Language", lang);
editor.commit();
}
public void getLocal() {
SharedPreferences sharedPreferences = getSharedPreferences("settings", Activity.MODE_PRIVATE);
String language = sharedPreferences.getString("My_Language", "");
setLocal(language);
}
}
答案 0 :(得分:1)
在onResume中尝试:
Locale locale = "LOADYOURLANGUAGE";
Locale.setDefault(locale);
Configuration config = getBaseContext().getResources().getConfiguration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
希望有帮助。