如何在Android的NavigationView上显示活动或片段?

时间:2019-10-16 13:59:18

标签: android drawerlayout navigationview side-menu

在Swift中,我们可以使用一个名为“ SideMenu”的库在SideMenu上显示viewController。

现在,我正在使用Android进行编码。我想在NavigationView中显示活动,我们只能显示一个Menu或标题。 我无法在NavigationView上显示活动或片段。

关于这个问题,您可以帮我还是给我一些建议吗?

ANDROID STUDIO NAVIGATION VIEW

XCODE SWIFT SIDE MENU

2 个答案:

答案 0 :(得分:1)

Android应用程序可以一次显示一项活动(最近已更改,但在您的情况下仍然如此)。在您的情况下,应为View或Fragment充气。只需将您的布局或片段放在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扩展了FrameLayout,因此,如果您要膨胀菜单,它将重叠。因此,您可能要删除:

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

enter image description here

答案 1 :(得分:0)

如果您使用的是Android导航组件,则可以查看实现此目的的完整详细信息,并将片段替换为与用户点击/选择drawer layout with navigation component相对应的部分
如果您不使用android导航组件,而仅使用抽屉布局,则可以看到此drawer layout

相关问题