我已经尝试制作App android更改语言而且我有问题,我的应用必须点击两次才能使用更改语言。
我的意思是,当我第一次单击英文按钮更改语言不起作用时,我再次点击,它有效。
这是我在Class Activity_Login.class中使用的方法
public void showLanguageOptions() {
String[] languages = {"Indonesia", "English"};
AlertDialog.Builder builder = new AlertDialog.Builder(Activity_Login.this);
builder.setTitle(getString(R.string.title_dialog_changelanguage));
builder.setIcon(R.drawable.ic_language);
builder.setItems(languages,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
if (arg1 == 0) {
((BaseActivity) getActivity()).saveDefaultLanguage(Cons.LANG_ID);
} else {
((BaseActivity) getActivity()).saveDefaultLanguage(Cons.LANG_EN);
}
((BaseActivity) getActivity()).finish();
Intent intent = new Intent(getActivity(),
Activity_Login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
getActivity().startActivity(intent);
}
});
builder.create().show();
}
这是我在BaseActivity.Class中的setuplanguage()
方法
public void setupLanguage() {
Locale locale = new Locale(getDefaultLanguage());
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
public String getDefaultLanguage() {
return sharedPreferences.getString(Cons.USER_LANGUAGE, Cons.LANG_ID);
}
public void saveDefaultLanguage(String lang) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Cons.USER_LANGUAGE, lang);
editor.commit();
}
我将方法setupLanguage称为Activity_Login.Class
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_login);
tv_language = (TextView) findViewById(R.id.tv_language);
String language = sharedPreferences.getString(Cons.USER_LANGUAGE, Cons.LANG_ID);
setupLanguage();
Log.d("bahasa",language);
tv_language.setText((language.equals(Cons.LANG_EN) ? getString(R.string.text_english) : getString(R.string.text_indonesia)));
tv_language.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showLanguageOptions();
}
});
}