2014-07-10 70 views
0

我有一個運行良好的導航抽屜。我的意思是,我可以瀏覽與導航抽屜相關的所有碎片(A,B,C,D)。我的問題出現在這裏。可以說我在片段A中,在這個片段中,我有一個按鈕,點擊時應該理想地用另一個片段替換片段Frag Z,並且一旦我在片段Z中可以返回片段A.將從導航抽屜創建的片段替換爲另一個動態

要實現這個我使用下面的代碼。然而,新的片段Z出現在片段A的頂部可能是什麼問題透明:

    Bundle bundle = new Bundle(); 
       bundle.putInt("int", 1); 
       bundle.putString("str","string"); 
       fragmentTransaction = getFragmentManager().beginTransaction(); 
       FragZ fragmentz = new FragZ(); 
       fragment.setArguments(bundle); 
       fragmentTransaction.replace(R.id.some_container, fragmentz); 
       fragmentTransaction.addToBackStack(null); 
       fragmentTransaction.commit(); 

編輯:

我已經找到一種解決方法,以該如下圖所示,但它不完全解決我的問題,因爲新顯示的片段仍然顯示,導航抽屜可以切換,但至少刪除了片段的覆蓋。我仍然想要一個解決方案來啓動一個獨立的片段

    Bundle bundle = new Bundle(); 
       bundle.putInt("int", 1); 
       bundle.putString("str","string"); 
       FragZ fragmentz = new FragZ(); 
       FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction(); 
       fragment.setArguments(bundle); 
       ft.replace(R.id.main, fragment); 
       ft.addToBackStack(null); 
       ft.commit(); 

回答

0

在您的活動中創建一個方法來啓動片段。無論何時想要顯示片段,只需使用數字或字符串來表示片段即可。您可以使用相同的功能從導航抽屜中啓動碎片。

例如:

public void displayView(int position) { 
    Fragment fragment = null; 
    currentFragmentNumber = position; 
    switch (position) { 
    case 0: 

     fragment = new frag1(); 

     break; 
    case 1: 
     fragment = new frag2(); 

     break; 
    case 2: 
     fragment = new frag3(); 

     break; 

    default: 
     break; 
    } 

    if (fragment != null) { 
     FragmentManager fragmentManager = getFragmentManager(); 
     fragmentManager.beginTransaction() 
       .replace(R.id.frame_container, fragment) 
       .addToBackStack("tag").commit();    

    } else { 
     // error in creating fragment 
     Log.e(TAG, "Error in creating fragment"); 
    } 
} 

您可以通過調用從活動這一功能:

((**ActivityName**) getActivity()).displayView(0); 
+0

這對任何片段活動對工作...不過我的情況是因爲獨特增加了導航抽屜。在你的情況下,我將只替換幀佈局(R.id.frame_container)中的後續片段,這正是我編輯我的問題,以顯示我可以實現但不是在尋找什麼,我想要一個新創建的情況片段不駐留在導航器抽屜中 –