How to handle Back Button to remove current fragme

2019-07-08 04:00发布

问题:

My MainMenu is the first launched activity or page which will show the MainPage as the Fragment

in this MainMenu,

a) it has a Left Drawer. When user click on an item in the drawer, it will be displayed as fragment.

In this MainPage,
b) it has dropdown menu in Action-Bar. when user click an item in the menu it will be displayed as fragment

The Problem:

1) User click an item in MainPage(b) :Action_bar dropdown menu, how to remove or not to show this current display fragment WHEN user click the back button and show the main page content

I tried below code, it does not work

public override void OnBackPressed()
{
  if (DrawerLayout != null && DrawerLayout.IsDrawerOpen(GravityCompat.Start))

        DrawerLayout.CloseDrawers();
  else
        base.OnBackPressed();
}

回答1:

You can add the fragment to the backstack of the fragment manager with this:

var ft = SupportFragmentManager.BeginTransaction();
ft.AddToBackStack(fragInfo.Tag);
ft.Commit();

I would recommend looking into the Android sample of MvvmCross. It handles a lot of things by default, like the backstack. https://github.com/MvvmCross/MvvmCross-AndroidSupport/tree/master/Samples