Search code examples
androiddrawerlayoutnavigationviewside-menu

How to display an activity or fragment on navigationView in Android?


In Swift, we can use a Library called "SideMenu" to show a viewController on the SideMenu.

Now, I'm coding in Android. I want to display activity in the NavigationView we can only display a Menu or header. I cannot show an activity or fragment on the NavigationView.

Can you help me or give me some advice about this problem?

ANDROID STUDIO NAVIGATION VIEW

XCODE SWIFT SIDE MENU


Solution

  • Android app can display one activity at once (it's changed recently but in your scenario it's still true). In your case you should inflate View or Fragment. Just put your layout or fragment inside NavigationView:

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">
    
        <include
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
        <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"
            app:headerLayout="@layout/nav_header_main"
            app:menu="@menu/activity_main_drawer">
    
            <TextView
                android:text="Custom View"
                android:layout_gravity="center"
                android:background="#ff0000"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
    
        </com.google.android.material.navigation.NavigationView>
    
    </androidx.drawerlayout.widget.DrawerLayout>
    

    NavigationView extends FrameLayout so if you will inflate menu it will overlap. Because of that you may want to delete:

    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer"
    

    enter image description here