4.3 KiB
Navigation Views
NavigationView is an easy way to display a navigation menu from a menu
resource.
This is most commonly used in conjunction with
DrawerLayout
to implement Material navigation
drawers.
Navigation drawers are modal elevated dialogs that come from the start/left
side, used to display in-app navigation links.
Design & API Documentation
Usage
NavigationView is a scrollable view that renders a menu resource
(R.menu.<something>) as a vertical list. It also renders a header view above
the menu.
<com.google.android.material.navigation.NavigationView
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start|left"
app:headerLayout="@layout/navigation_header"
app:menu="@menu/my_navigation_items" />
Available flags
app:menupoints to a menu resource that will be rendered byNavigationViewapp:headerLayoutpoints to a layout resource to use as a header for theNavigationView
Handling selection
You can use setNavigationItemSelectedListener to listen to item selection and
implement your navigation logic.
Header views
You can only add one header in the XML layout, but you can add multiple header
views programmatically with addHeaderView(View) (even if you already added one
in the XML layout). You can use getHeaderView(int) to get any of the header
views at runtime.
If you need to access the header view you added in the XML layout, that will
always be the first header view, so you can get it with getHeaderView(0).
Implementing Material navigation drawers
Implementing navigation drawers is the most common use for NavigationView,
this section guides you on how to use NavigationView in that context.
- Wrap your activity's content in a
DrawerLayout. In the example below, the activity's content is the CoordinatorLayout. - Keep your main content as the first child of that
DrawerLayout. - Add your
NavigationViewwithandroid:layout_gravity="start|left"andandroid:height="match_parent".
Assuming your Activity's content is in a CoordinatorLayout you may have something like this:
<androidx.drawerlayout.widget.DrawerLayout>
<androidx.coordinatorlayout.widget.CoordinatorLayout>
<!-- Your content goes here -->
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.navigation.NavigationView
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start|left"
app:headerLayout="@layout/navigation_header"
app:menu="@menu/my_navigation_items" />
</androidx.drawerlayout.widget.DrawerLayout>
Related Concepts
There are other navigation patterns you should be aware of
- Hierarchical navigation. See also Navigation with Back and Up
- Swipeable tabs using TabLayout and ViewPager
- BottomNavigationView for when you have only 3 to 5 very well defined navigation categories
You should familiarize yourself with the most common use for NavigationView,
Creating a Navigation Drawer - Guide.