2014-10-02 58 views
1

我有一個基於Android文檔中的example的導航抽屜。拉回抽屜裏面

當您打開導航抽屜時,它會在抽屜內顯示MainMenuFragment。當您選擇一個菜單項時,它會用SubMenuFragment替換抽屜內的碎片。這對後退按鈕很好。

按下後退按鈕總是關閉抽屜,但我想要使用後退按鈕在顯示SubMenuFragment時在抽屜中顯示MainMenuFragment。如何處理導航抽屜內的後退按鈕以替換抽屜內顯示的碎片。

更換抽屜內部的碎片並不是問題。我無法弄清楚如何停止關閉抽屜的後退按鈕,而是讓它顯示MainMenuFragment

我的主要活動XML(簡稱):

<android.support.v4.widget.DrawerLayout ....> 
    <FrameLayout android:id="@+id/container" .../> 
    <FrameLayout android:id="@+id/drawer" android:layout_gravity="start" .../> 
</android.support.v4.widget.DrawerLayout> 

和我班的相關部分:

public class MainActivity extends Activity { 
    ... 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     getFragmentManager().beginTransaction() 
      .replace(R.id.drawer, new MainMenuFragment()).commit(); 

     // setup DrawerLayout and ActionBarDrawerToggle 
     ... 
    } 

    private void showSubMenu() { 
     getFragmentManager().beginTransaction() 
      .replace(R.id.drawer, new SubMenuFragment()).commit(); 
    } 
} 

回答

1

我已經在不同的情況下,之前使用是片段添加到碎片堆棧中。

所以當更改片段首先將其添加到後退堆棧中。

getFragmentManager().beginTransaction() 
     .replace(R.id.drawer, new MainMenuFragment()).addToBackStack(null).commit(); 

而當處理回來時,請執行以下操作。

int count = getSupportFragmentManager().getBackStackEntryCount(); 

if(count > 1) 
     getSupportFragmentManager().popBackStack(); 

試試看看它是否有效。

還檢查了這一點:http://developer.android.com/training/implementing-navigation/temporal.html#back-fragments

+0

謝謝,但你怎麼處理了?當您打開導航抽屜並按回時,從不會調用「活動」的「onBackPressed」。 – rve 2014-10-02 15:32:12

+0

設置你的抽屜佈局爲:'mDrawerLayout.setFocusableInTouchMode(false);「onBackPressed()應該工作,如果不嘗試onKeyDown – 2014-10-02 15:48:38

+0

實際上,只需設置'setFocusableInTouchMode(false)'使後退按鈕在抽屜中工作,不需要任何額外的代碼。但是,現在抽屜不會關閉,'onBackPresses()'仍然不會被調用。 – rve 2014-10-03 06:53:13