Chindara
Chindara

Reputation: 138

Navigation Drawer in Multiple Activities in Xamarin Android

I'm trying to create a navigation drawer in Xamarin using Visual Studio 2017. I created the navigation drawer after some research in google. But when I try to open activities from the menu, navigation drawer disappears.

I want to have my navigation drawer in all my activities, without repeating it in all activities.

Link to my project: https://github.com/Chindara/XamarinAndroidNavigationDrawer

Updated link: https://github.com/Chindara/XamarinAndroid-NavigationDrawer

Upvotes: 2

Views: 2667

Answers (1)

York Shen
York Shen

Reputation: 9084

When you click a menu item, you should navigate to a Fragment instead of an Activity, Framework can also display the user interface. If you doing this, when you select a Fragment, the navigation drawer will always in your Activitiy, like this. Here is the document about how to use Fragment in Xamarin.

When you select your menu item :

navigationView.NavigationItemSelected += (sender, e) =>
        {
            e.MenuItem.SetChecked(true);

            FragmentTransaction ft = this.FragmentManager.BeginTransaction();
            if (e.MenuItem.ItemId == Resource.Id.nav_MGrade)
            {
                MGradeFragment mg = new MGradeFragment();
                // The fragment will have the ID of Resource.Id.fragment_container.
                ft.Replace(Resource.Id.ll, mg);
            }
            else if(e.MenuItem.ItemId == Resource.Id.home)
            {
                //...
            }
            //...

            // Commit the transaction.
            ft.Commit();
            drawerLayout.CloseDrawers();
        };

MGradeFragment.class, did the same thing as your MGradeActivity:

public class MGradeFragment : Fragment
{
    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your fragment here
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Use this to return your custom view for this Fragment
        // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

        View view = LayoutInflater.From(Activity).Inflate(Resource.Layout.MGradesView, null);
        return view;
    }
}

The MGradeFragment will replace the LinearLayout in your Main.axml :

   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:id="@+id/ll"
        >
        <include
            layout="@layout/toolbar" />
    </LinearLayout>

And in your toolbar.axml, modify your code :

<android.support.design.widget.CoordinatorLayout 
    ....
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">//Change match_parent to wrap_content

Upvotes: 4

Related Questions