2013-02-20 15 views
0

我的问题与我的应用程序有关。我正在给用户一个改变语言的选项。使用以下代码可以很好地工作:Android应用程序在从睡梦中醒来时更改语言

public void jezik_slo(View view) 
{ 
    Locale locale = new Locale("SI_sl"); 
    Locale.setDefault(locale); 
    Configuration config = new Configuration(); 
    config.locale = locale; 
    this.getApplicationContext().getResources().updateConfiguration(config, null); 
} 

public void jezik_ang(View view) 
{ 
    Locale locale = new Locale("en_US"); 
    Locale.setDefault(locale); 
    Configuration config = new Configuration(); 
    config.locale = locale; 
    this.getApplicationContext().getResources().updateConfiguration(config, null); 
} 

除锁定手机或手机进入睡眠状态,然后苏醒之外,一切都可以。此时应用程序使用DEFAULT字符串值(值为-EN) 我该如何解决这个问题?

回答

0

两个元素: - 为什么在方法 中有参数“查看视图” - 如果要保存选定的语言,可以将它保存在某处。像 “SharedPreference”:

附加保存方法:

private static final String BASE_LANGUAGE = "base", KEY_LANGUAGE = "lang"; 

private void saveLanguage(String lang) { 
SharedPreferences sp = this.getSharedPreferences(BASE_LANGUAGE, Context.MODE_PRIVATE); 
Editor editor = sp.edit(); 
editor.putString(KEY_LANGUAGE, lang); 
editor.commit(); 
} 

添加get方法:

private String getLanguage() { 
SharedPreferences sp = this.getSharedPreferences(BASE_LANGUAGE, Context.MODE_PRIVATE); 
return sp.getString(KEY_LANGUAGE, "en_US"); //en_US is default language 
} 

删除重复代码

public void jezik(String lang) 
{ 
    Locale locale = new Locale(lang); 
    Locale.setDefault(locale); 
    Configuration config = new Configuration(); 
    config.locale = locale; 
    this.getApplicationContext().getResources().updateConfiguration(config, null); 
    saveLanguage(lang); 
} 

加载的语言,在“的onCreate “方法,试试这个:

jezik(getLanguage()); 

在此代码中,“this”是Activity或Context。对不起,我的英文,我希望这是你想要的

相关问题