当我更改项目中的语言时,但是当我关闭项目并重新打开时,语言是默认的。
如何检查此问题?
这是我的代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Locale myLocale;
private Button btn_en, btn_ku,btn_ar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadLocale();
this.btn_en = (Button)findViewById(R.id.btn_en);
this.btn_ku = (Button)findViewById(R.id.btn_ku);
this.btn_ar = (Button)findViewById(R.id.btn_ar);
this.btn_en.setOnClickListener(this);
this.btn_ku.setOnClickListener(this);
this.btn_ar.setOnClickListener(this);
}
public void loadLocale()
{
String langPref = "Language";
SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
String language = prefs.getString(langPref, "");
changeLang(language);
}
public void changeLang(String lang)
{
if (lang.equalsIgnoreCase(""))
return;
myLocale = new Locale(lang);
saveLocale(lang);
Locale.setDefault(myLocale);
android.content.res.Configuration config = new android.content.res.Configuration();
config.locale = myLocale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
//updateTexts();
}
public void saveLocale(String lang)
{
String langPref = "Language";
SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(langPref, lang);
editor.commit();
}
private void updateTexts()
{
}
public void onClick(View v) {
String lang = "en";
switch (v.getId()) {
case R.id.btn_en:
lang = "en";
finish();
startActivity(getIntent());
break;
case R.id.btn_ku:
lang = "fa";
finish();
startActivity(getIntent());
break;
case R.id.btn_ar:
lang = "ar";
finish();
startActivity(getIntent());
break;
default:
break;
}
changeLang(lang);
}}
答案 0 :(得分:0)
在onResume()中调用loadLocale方法它会起作用。
因为首先调用onCreate()方法,如果您通过转到主屏幕或启动另一个活动来暂停活动,则调用onPause()方法。
如果你再次恢复应用意味着它会调用onCreate()方法(已经被破坏),否则它只调用onResume()
@Override
public void onResume(){
super.onResume();
loadLocale();
}
答案 1 :(得分:0)
我遇到了同样的问题,对我来说,解决方案是每次在setContentView()之前的所有活动的oncreate()中设置新的语言环境! 像这样:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadLanguage();
setContentView(R.layout.activity_avval);
}
private void loadLanguage()
{
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
String lng = Application.instance().settings.getString("deflang", "def");
if (!lng.equalsIgnoreCase("def")) {
Resources res = this.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
Locale locale = new Locale(lng);
conf.setLocale(locale); // API 17+ only.
res.updateConfiguration(conf, dm);
Locale.setDefault(locale);
}
}
}