Navigation Drawer with Material 3 (The Easy Way)
Introduction
Hello there, readers. I discovered an easy and quick way to work with side navigation drawers in Android using Material 3. I tried the old methods available on YouTube and other platforms, but they are difficult to build. So I devised this method to make it simple. (This approach is for MDC-Android)
Get started
Setting Up Dependencies
Material Components for Android are available through Google's Maven Repository. To use it:
Open the
build.gradle
file for your application.Make sure that the repositories section includes Google's Maven Repository
google()
. For example,
allprojects {
repositories {
google()
jcenter()
}
}
- Add the library to the dependencies section:
dependencies {
// ...
implementation 'com.google.android.material:material:<version>'
// ...
}
check the latest version here
Visit Google's Maven Repository or MVN Repository to find the latest version of the library.
Creating Menu Items
Adding Menu Items for Display in the Navigation Drawer Layout
dashboard_navigation_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/main_item"
android:title="Hello">
<menu>
<item
android:id="@+id/inbox_item"
android:checkable="true"
android:title="hola" />
<item
android:id="@+id/outbox_item"
android:checkable="true"
android:title="amazing" />
</menu>
</item>
</menu>
Building UI
We'll add a drawer layout to open and close the navigation menu options, and we'll use AppBarLayout to create an app bar to show the drawer, and MaterialToolbar will be the icon we'll click to open and close the drawer.
dashboard.xml
<androidx.drawerlayout.widget.DrawerLayout
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintStart_toStartOf="parent"
tools:openDrawer="end">
<com.google.android.material.navigation.NavigationView
android:id="@+id/navigation_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/dashboard_navigation_bar" />
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/topAppBar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:navigationIcon="@drawable/dashboard_menu" />
</com.google.android.material.appbar.AppBarLayout>
</androidx.drawerlayout.widget.DrawerLayout>
Make It Work (Functional Code)
UserDashBoard.java
DrawerLayout drawerLayout;
Toolbar toolbar;
drawerLayout = findViewById(R.id.drawer_layout);
// navigationView = findViewById(R.id.navigation_view);
toolbar = findViewById(R.id.topAppBar);
//setting menu listener
toolbar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(drawerLayout.isOpen()){
drawerLayout.close();
}else{
drawerLayout.open();
}
}
});