2017-04-11 129 views
0

我有一個Android應用程序,其中包含1 base activity和一些片段。可以使用DrawerLayout中的NavigationView來更改它們。用戶可以在其中一個片段中更改應用程序的語言,當我重新啓動應用程序時,我希望用戶返回到特定的片段。Android更改導航視圖片段

=====DrawerLayout===== 
1. Fragment Home -> This is the starting fragment 
2. Fragment One 
3. Fragment Settings -> Users change the language here. 

當用戶更改語言,在base activity的方法被調用,我改變了語言環境,並呼籲重新創建()。這將刷新應用程序,使用新語言顯示片段主頁。我想以編程方式更改爲片段設置。

navigationView.<METHOD?> 
+0

你爲什麼不直接從活動的回調設置活性片段? –

+0

因爲我需要更改應用程序的語言。它不會更新,除非我調用recreate()。 –

回答

1

爲了解決您的問題,您可以保存特殊狀態並重新創建活動。當活動重新創建時,它會知道它需要使用保存的狀態移動到設置頁面。

您的活動試試這個:

static final String SHOW_SETTINGS = "SHOW_SETTINGS"; 
private boolean showSettings = false; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    createLayoutAndDoOtherOnCreateThings(); 

    // Check whether we're recreating a previously destroyed instance 
    if (savedInstanceState != null) { 
     // Restore value of members from saved state 
     if (savedInstanceState.getBoolean(SHOW_SETTINGS, false)) { 
      showSettingsFragment(); 
    } 
} 

@Override 
public void onSaveInstanceState(Bundle savedInstanceState) { 
    savedInstanceState.putBoolean(SHOW_SETTINGS, showSettings); 
    // Always call the superclass so it can save the view hierarchy state 
    super.onSaveInstanceState(savedInstanceState); 
} 

private void callRecreateWithSettingsWhenRecreating() { 
    showSettings = true; 
    recreate(); 
}