Tuesday, October 15, 2019

Navigation Drawer or Navigation View in Androidx



You first need to import some dependencies into your project related to the navigation view in androidx, which are:

implementation 'androidx.navigation:navigation-fragment:2.1.0'

implementation 'androidx.navigation:navigation-ui:2.1.0'

Then you need to create a menu for your navigation drawer items which could look like this:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_profile"
        android:icon="@drawable/user"
        android:title="@string/user"/>
    <item android:id="@+id/menu_dashboard"
        android:icon="@drawable/home"
        android:title="Dashboard"/>
    <item android:id="@+id/menu_history"
        android:icon="@drawable/history"
        android:title="History"/>
    <item android:id="@+id/menu_TADA"
        android:icon="@drawable/wallet"
        android:title="TADA"/>
    <item
        android:id="@+id/menu_logOut"
        android:icon="@drawable/ic_power_settings_new_black_24dp"
        android:title="Logout"/>
</menu>


Then you need to create fragments for every single item in the navigation drawer which you wanted to open on a new page, for example, I have 4 items in the menu which are home, profile, history, and logout.
I just don't want to create any new page for the logout option I just want to show a dialog with yes and cancel options, so you no need to create a fragment for the logout option but if you want to show a UI you need to create a fragment for that.

And in this case, I created fragments for HomeFragment, ProfileFragment, TADAFragment, and HistoryFragment.

And after creating fragments you need to declare a host fragment in your main activity's layout, so your layout file for MainActivity will be like this:

<androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/drawer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">
        
        <fragment
            android:id="@+id/nav_host_fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="androidx.navigation.fragment.NavHostFragment"
            app:defaultNavHost="true" />

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            android:background="@color/white"
            app:headerLayout="@layout/nav_header_main"
            app:itemIconTint="@color/colorPrimary"
            app:menu="@menu/activity_main_drawer"/>
    </androidx.drawerlayout.widget.DrawerLayout>

And the header layout in the navigation view could be anything you want to add and the menu is what we already created we just need to mention it here.

Then you should implement your MainActivity with NavigationView.OnNavigationItemSelectedListener and then you need to click Alt+Enter to get the suggestion of implementing methods of this implementation.

Then you should mention what to do with your Navigation Items Click Listener and I did this:

@Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        int id = menuItem.getItemId();
        switch (id) {
            case R.id.menu_profile:
                loadFragment(new ProfileFragment());
                break;
            case R.id.menu_dashboard:
                loadFragment(new HomeFragment());
                break;
            case R.id.menu_history:
                loadFragment(new HistoryFragment());
                break;
            case R.id.menu_TADA:
                loadFragment(new TADAFragment());
                break;
            case R.id.menu_logOut:
                logout();
                break;
        }
        return false;
    }

And the method loadFragment is a method that takes a fragment as a parameter and set it to our host fragment which is present in our MainActivity's layout file and that method looks like this:

private void loadFragment(Fragment fragment) {
        getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        String backStateName = fragment.getClass().getName();

        FragmentManager manager = getSupportFragmentManager();
        boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0);

        if (!fragmentPopped && manager.findFragmentByTag(backStateName) == null) { 

            FragmentTransaction ft = manager.beginTransaction();
            backStateName = fragment.getClass().getName();
            fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
            if (!fragmentPopped) {
                ft.replace(R.id.nav_host_fragment, fragment);
                if (drawer.isDrawerOpen(GravityCompat.START))
                    drawer.closeDrawer(GravityCompat.START);
            }
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.addToBackStack(backStateName);
            ft.commit();
        }
    }

Now you need to set your navigation drawer which is done in the onCreate method your MaainActivity:

Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        drawer = findViewById(R.id.drawer);
        navView = findViewById(R.id.nav_view);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
        navController = Navigation.findNavController(this, R.id.nav_host_fragment);

        appBarConfiguration = new AppBarConfiguration.Builder(R.id.menu_profile, R.id.menu_dashboard,
                R.id.menu_history, R.id.menu_TADA, R.id.menu_logOut).setDrawerLayout(drawer).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
        navView.setNavigationItemSelectedListener(this);
        loadFragment(new HomeFragment());
And that's pretty much it now your Navigation Drawe will run perfectly.





No comments:

Post a Comment