Pietv
Pietv

Reputation: 225

MvvmCross - Change Hamburger menu to back button

I'm using the XPlatformMenus sample Android project available at https://github.com/MvvmCross/MvvmCross-Samples/tree/master/XPlatformMenus

What I want to do is, when the user navigates to the InfoFragment, that the Hamburger menu icon change to a back arrow and when pressed the app navigates to the previous view/fragment, which in this case is the HomeFragment.

I've seen a method called ShowBackButton on the MainActivity, but it is not called from anywhere, so I've added it's code to the BaseFragment's OnCreateView, where it checks the ShowHamurgerMenu bool. I've added an else, and the code looks something along these lines:

                if (ShowHamburgerMenu)
            {
                mainActivity.SupportActionBar?.SetDisplayHomeAsUpEnabled(true);

                DrawerToggle = new MvxActionBarDrawerToggle(
                    Activity, // host Activity
                    mainActivity.DrawerLayout, // DrawerLayout object
                    Toolbar, // nav drawer icon to replace 'Up' caret
                    Resource.String.drawer_open, // "open drawer" description
                    Resource.String.drawer_close // "close drawer" description
                );

                DrawerToggle.DrawerOpened += (sender, e) => mainActivity?.HideSoftKeyboard();
                mainActivity.DrawerLayout.AddDrawerListener(DrawerToggle);
            }
            else
            {
                mainActivity.SupportActionBar?.SetDisplayHomeAsUpEnabled(false);

                DrawerToggle = new MvxActionBarDrawerToggle(
                    Activity, // host Activity
                    mainActivity.DrawerLayout, // DrawerLayout object
                    Toolbar, // nav drawer icon to replace 'Up' caret
                    Resource.String.drawer_open, // "open drawer" description
                    Resource.String.drawer_close // "close drawer" description
                );

                DrawerToggle.DrawerIndicatorEnabled = false;
                //mainActivity.DrawerLayout.SetDrawerLockMode(DrawerLayout.LockModeLockedClosed);

                //mainActivity.SupportActionBar?.SetDisplayHomeAsUpEnabled(false);
                //mainActivity.ShowBackButton();
            }

I set ShowHamburgerMenu = false; in the InfoFragment's OnCreateView. So far I managed to hide the Hamburger menu, but are not able to show a back button.

Any advice or guidance or even a reference to some articles that might help would be greatly appreciated.

Thank you very much!

Upvotes: 1

Views: 939

Answers (1)

Pietv
Pietv

Reputation: 225

Got this working by handling the Toolbar's NavigationClick event in the following manner:

    private void Toolbar_NavigationClick(object sender, Toolbar.NavigationClickEventArgs e)
    {
        var mainActivity = Activity as MainActivity;
        mainActivity?.OnBackPressed();
    }

Upvotes: 1

Related Questions