2015-11-05 33 views
1

我用下面的代碼來改變語言:使用SharedPreferences更改啓動活動中的應用程序語言?

public void setLocale(String languageToLoad){ 
    Locale locale = new Locale(languageToLoad); 
    Locale.setDefault(locale); 
    Configuration config = new Configuration(); 
    config.locale = locale; 
    getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics()); 
    Intent intent = new Intent(getApplicationContext(), MainActivity.class); 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    startActivity(intent); 
} 

我的問題是,當我嘗試加載「區域設置」使用SharedPreferences它似乎是陷阱在一個循環中,因爲清爽的活動。所以我怎樣才能加載最後的定位在開始活動。 在此先感謝。

+0

調用setLocale的代碼在哪裏? –

+0

您可以比較用設置的區域設置設置的區域設置嗎?如果他們是一樣的,什麼都不做? –

回答

0

我找到了答案:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    //some code here 
    if (last_local.equals("fa") && current_local.equals("en")) 
     setLocale("fa"); 
    //some code here 
} 

public void setLocale(String languageToLoad){ 
    Locale locale = new Locale(languageToLoad); 
    Locale.setDefault(locale); 
    Configuration config = new Configuration(); 
    config.locale = locale; 
    getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); 
    SharedPreferences Settings=getSharedPreferences("Last Setting",1); 
    Settings.edit().putString("Locale Status", languageToLoad).commit(); 
    Intent intent = new Intent(getApplicationContext(), MainActivity.class); 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    startActivity(intent); 
} 

我的問題是,我保存loace的onStop()方法,它是循環的原因。

0

您不需要再次啓動活動。您只需通過調用setContentView()來重新創建視圖和佈局。

相關問題