我想用微调器制作多语言应用程序,我遇到了错误。更改语言时,我的应用程序创建了这么多页面,在这种情况下我调用MainActivity页面。翻译语言时也不会出现进度对话框。 我怎么能解决它? 这是我的代码:
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting_page);
setDefaultToolbar(true);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Translating...");
Spinner spinner = findViewById(R.id.sp_language);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.language, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (pos == 1) {
setLocale("in");
progressDialog.show();
}
else if (pos == 2) {
setLocale("en");
progressDialog.show();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public void setLocale(String lang) {
Locale myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
this.recreate();
Intent refresh = new Intent(this, MainActivity.class);
startActivity(refresh);
progressDialog.dismiss();
}
答案 0 :(得分:0)
请尝试以下代码,以这种方式更改区域设置后,重新启动您的活动。
public static Context onAttach(Context context, String defaultLanguage) {
// String lang = getLanguageFromPrefs(context);
return setLocale(context, defaultLanguage);
}
public static Context setLocale(Context context, String language) {
// saveLanguageToPrefs(language,context);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return updateResources(context, language);
}
return updateResourcesLegacy(context, language);
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration configuration = new Configuration(context.getResources().getConfiguration());
configuration.setLocale(locale);
return context.createConfigurationContext(configuration);
}
@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Resources resources = context.getResources();
Configuration configuration = new Configuration(context.getResources().getConfiguration());
if (Build.VERSION.SDK_INT >= 17) {
configuration.setLocale(locale);
} else {
configuration.locale = locale;
}
context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());
return context;
}
<强>更新强>
现在这样做:
Context context=onAttach(MainActivity.this,"YourLanguage") //eg. ar or en,fr...
this.recreate();
答案 1 :(得分:0)
试试这个:
Intent intent = getIntent();
finish();
startActivitiy(intent);