0

如何在新設計支持導航抽屜中切換片段?我在Cheesesquare Github上找到了關於如何使用TabLayout切換片段的示例代碼,但不是導航抽屜。那是一樣的嗎?我也不想在切換時重新創建片段,而是像TabLayout那樣保留片段實例,並且片段的內容是用戶如何離開它的。Android開關新設計中的片段支持導航抽屜

回答

0

寫一些像這樣的代碼:

navigationView.setNavigationItemSelectedListener(
     new NavigationView.OnNavigationItemSelectedListener() { 
    @Override 
    public boolean onNavigationItemSelected(MenuItem menuItem) { 
     menuItem.setChecked(true); 
     mDrawerLayout.closeDrawers(); 
     switch (menuItem.getItemId()) { 
      case R.id.your_menu_id: 
       getSupportFragmentManager().beginTransaction().replace(R.id.fragment, getFragment(), "SET_A_TAG").addToBackStack("SET_A_TAG").commit(); 
       break; 
     } 
     return true; 
    } 
}); 

private YourFragment getFragment() { 
    YourFragment f = getSupportFragmentManager().findFragmentByTag("SET_A_TAG"); 
    if (f == null) { 
     f = new YourFragment(); 
    } 
    return f; 
} 
+0

但是,這每創建一個新的片段,我點擊該項目。我不想那樣。我希望它保持不變,所以當我切換到另一個片段並返回它仍然具有相同的視圖時,我在EditTexts中輸入的所有文本都一樣 – qwertz

+0

@qwertz請參閱我的編輯以獲取片段已存在。 –

+0

非常感謝:) – qwertz

0
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
android:id="@+id/drawer_layout" 
android:layout_height="match_parent" 
android:layout_width="match_parent" 
android:fitsSystemWindows="true"> 

<include layout="@layout/include_list_viewpager"/> 

<FrameLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@id/fragmentContainer"/> 

<android.support.design.widget.NavigationView 
    android:id="@+id/nav_view" 
    android:layout_height="match_parent" 
    android:layout_width="wrap_content" 
    android:layout_gravity="start" 
    android:fitsSystemWindows="true" 
    app:headerLayout="@layout/nav_header" 
    app:menu="@menu/drawer_view"/> 

像這樣的事情?

+0

我認爲你不明白我的問題,也有一個答案已經 – qwertz

+0

哦,她以爲你是另一個人。是的,除非你必須將listpager和framelayout放在一起,如線性佈局 – qwertz

+0

好的,謝謝。因爲我不知道如何顯示另一個Tablayout的片段。問題是,當我把新片段放在Fragmentcontainer中,那麼沒有顯示任何工具欄。因爲它被新片段隱藏 – observer