2014-02-19 21 views
0

我已經在我的應用中實現了選擇GUI語言的選項,但是當選擇新語言時,我無法使其刷新屏幕。
通過ListPreference進行選擇,因此存在兩個問題: 1.刷新其中選擇語言的Preference頁面。 2.當應用程序啓動時,我將Locale設置爲MainActivityonCreate(),但MainActivity佈局永遠不會使用新的選定區域更新。 (所有其他屏幕更新,以便設置代碼是好的)。如何在Android中將新的語言環境應用到當前屏幕

這裏是設置新的區域設置代碼:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx); 

    String langKey = ctx.getString(R.string.shared_options_select_language_key); 
    String langDefault = ctx.getString(R.string.shared_options_select_language_default_value); 
String appLanguage = preferences.getString(langKey, langDefault); 

Locale locale = null; 
if (appLanguage.equals(langDefault)) {     
    locale = new Locale(Resources.getSystem().getConfiguration().locale.getLanguage()); 
} else { 
    String[] languageInfo = appLanguage.split("_"); 
    if (languageInfo.length > 1) { 
     locale = new Locale(languageInfo[0], languageInfo[1]); 
    } else { 
     locale = new Locale(appLanguage); 
    } 
} 
if (appLanguage.contains(currentLang)) { 
    return false; 
} 
Locale.setDefault(locale); 
Configuration config = new Configuration(); 
config.locale = locale; 

act.getBaseContext().getResources().updateConfiguration(config, act.getBaseContext().getResources().getDisplayMetrics()); 

謝謝

回答

0

答案是正確的設置屏幕內容之前調用setLocale的位置:

setLocale(); 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 
0

嘗試刷新在MainActivity選擇新的區域設置

使用後此重新加載的主要活動或任何活動

public void refrehs_me() 
{ 
    Intent intent = getIntent(); 
    finish(); 
    startActivity(intent); 
} 

編輯:正如我可以從你的說明在上面保存在共享首選項中選擇的新語言環境。

在名爲(locale_changed)的共享首選項中創建一個新的布爾鍵 - 當用戶選擇一個新的語言環境時將此鍵設置爲(TURE),並在設置新的語言環境檢查此鍵後設置onCreate if(TRUE)set它將(FALSE)並重新加載活動。

第二次去,它將不會循環,直到用戶再次更改語言環境首選項爲止,鍵仍然是(FALSE)。

+0

的問題是它會做這樣的循環,因爲我每次都設置語言環境。 Locale保存了,所以我可以檢查'setLocale'是否需要? – SagiLow

+0

爲什麼不只是防止UI「刷新」,如果區域設置==與以前相同。 – dymmeh

+0

我試着通過getResources()。getConfiguration()。locale.getLanguage()方法獲得'previous',但它總是返回'EN'而不是設置語言,就像'Locale'在退出應用時重置一樣。 – SagiLow

相關問題