首页 > 解决方案 > 如何在 Android 中使用 Navigation Drawer 设置导航组件?

问题描述

如何使用导航抽屉设置导航组件?如何在我的应用程序中使用它?

一个Activity可以完成所有事情吗?

如何仅使用一个 Activity 和具有动态工具栏可见性的片段来处理工具栏可见性。此外,还有一些碎片我需要关闭抽屉并使其无法访问。

这个问题是一个自我回答的问题,更像是一个教程而不是现实生活中的 QA。

标签: androidnavigation-drawerandroid-architecture-navigation

解决方案


如何使用导航抽屉设置导航组件?

如何在我的应用程序中使用它?

当涉及到导航组件时,导航抽屉的设置略有不同。

请注意,如果您创建一个带有抽屉导航的新应用程序,则不需要当前教程。但是,如果您决定在应用程序的后期添加抽屉,我将在这里解释一些可能看起来很奇怪的事情

首先,您需要设置activity_main.xmlMainActivity为导航架构做好准备:

<?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" />

</androidx.drawerlayout.widget.DrawerLayout>

app_bar_main只是:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_main" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

content_main是你的片段将被保存的地方:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>

你应该知道的事情:活动不能有一个 AppBar 设置在AndroidManifest.xml

android:theme="@style/AppTheme.NoActionBar"

如果您app:menu="@menu/activity_main_drawer"NavigationView标签中注意到,片段名称应该与它们在 中的相同mobile_navigation.xml

<group android:checkableBehavior="single">
        <item
            android:id="@+id/homeFragment"
            android:icon="@drawable/ic_menu_camera"
            android:title="@string/menu_home" />
        <item
            android:id="@+id/galleryFragment"
            android:icon="@drawable/ic_menu_gallery"
            android:title="@string/menu_gallery" />
        <item
            android:id="@+id/slideshowFragment"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="@string/menu_slideshow" />
        <item
            android:id="@+id/toolsFragment"
            android:icon="@drawable/ic_menu_manage"
            android:title="@string/menu_tools" />
    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/shareFragment"
                android:icon="@drawable/ic_menu_share"
                android:title="@string/menu_share" />
            <item
                android:id="@+id/sendFragment"
                android:icon="@drawable/ic_menu_send"
                android:title="@string/menu_send" />
        </menu>
    </item>

</menu>

这样,下面将要解释的内容将无需调用onCreateOptionsMenu来检测点击。Android 团队已经为我们解决了这个问题。关注下方。

到目前为止,这与我们实际使用的通常抽屉设置并没有太大区别。但是,我们需要在应用程序的逻辑部分进行一些配置。所以让我们打开MainActivity.kt。首先你需要这些:

  private var appBarConfiguration: AppBarConfiguration? = null
  private var drawerLayout: DrawerLayout? = null
  private var toolbar: Toolbar? = null
  private var navController: NavController? = null

之后在您的onCreate方法中:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar) //set the toolbar

        drawerLayout = findViewById(R.id.drawer_layout)
        val navView: NavigationView = findViewById(R.id.nav_view)
        navController = findNavController(R.id.nav_host_fragment)
        appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.homeFragment,
                R.id.galleryFragment,
                R.id.slideShowFragment,
                R.id.toolsFragment,
                R.id.shareFragment,
                R.id.sendFragment,
                R.id.loginFragment,
                R.id.phoneConfirmationFragment
            ), drawerLayout
        )

        setupActionBarWithNavController(navController!!, appBarConfiguration!!) //the most important part
        navView.setupWithNavController(navController!!) //the second most important part

      //other things unrelated
    }

让我们看看这里发生了什么:

首先,您需要对navController. 这AppBarConfiguration只是一个包含将作为顶级目的地打开的片段的类。这意味着将在它们之后打开的片段将从片段返回堆栈中释放当前片段。告诉AppBarConfiguration我们我们也有一个抽屉很重要(在构造函数中作为参数传递)。

在下面,您将有一个名为的方法onSupportNavigateUp()

override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp(appBarConfiguration!!) || super.onSupportNavigateUp()
    }

此方法与向上返回按钮有关。但是如果你有抽屉导航,你就不需要太多了。当您在后台堆栈(或至少两个)上添加了很多片段时,这真的很方便。

一个Activity可以完成所有事情吗?

当然是!但是在条件导航方面仍然需要做更多的工作。就像你想显示不属于抽屉应用程序的片段时一样。但谷歌仍然在这方面取得了巨大的进步。您可以参考这里的条件导航。

如何仅使用一个 Activity 和具有动态工具栏可见性的片段来处理工具栏可见性。此外,还有一些碎片我需要关闭抽屉并使其无法访问。

您可以addOnDestinationChangedListener使用navController

navController.addOnDestinationChangedListener { _, destination, _ ->
            when (destination.id) {
                R.id.loginFragment, R.id.registerFragment, R.id.phoneConfirmationFragment -> {
                    toolbar?.visibility = View.GONE
                    drawerLayout?.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
                }
                else -> {
                    toolbar?.visibility = View.VISIBLE
                    drawerLayout?.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
                }
            }
        }

现在您的应用程序上有一个抽屉和导航组件。


推荐阅读