Android 如何将NavigationDrawer从活动模板添加到其他活动?

Android 如何将NavigationDrawer从活动模板添加到其他活动?,android,android-fragments,Android,Android Fragments,我一直在玩Android Studio的抽屉菜单活动模板,因为我以前从未使用过抽屉菜单。这是布局文件 <android.support.v4.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.c

我一直在玩Android Studio的抽屉菜单活动模板,因为我以前从未使用过抽屉菜单。这是布局文件

<android.support.v4.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">

    <!-- Includes a Toolbar and FloatingActionButton. Generated by Android Studio-->
    <include layout="@layout/app_bar_drawer_menu" android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.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_drawer_menu"
        app:menu="@menu/activity_side_menu_drawer" />

</android.support.v4.widget.DrawerLayout>

Android Studio还生成了一个活动类作为模板的一部分。我的应用程序也有一个使用线性布局的主活动。我想使用片段将抽屉菜单添加到主活动和其他活动中,但我不确定如何执行此操作。我是否需要创建一个新的fragment子类,并为fragment类修改drawermenualActivity的回调方法?那么我是否要在activity_main.xml中添加一个片段标记?

这可能是您需要考虑的问题

理想情况下,您希望通过使用fragment transaction并调用replace来交换位于xml中的容器中的片段,以用于MainActivity。这将允许您重新使用容器,并为整个应用程序提供抽屉

否则,您将需要在每个创建大量额外代码的活动中包含抽屉,或者不提供抽屉,这取决于您可能能够侥幸逃脱的活动

因此,抽屉可以处理通过事务交换的片段,而不适合进行其他活动。这是你需要设计的东西

请创建一个新项目,为活动生成一个抽屉,然后从那里开始。还可以阅读android开发者教程中关于通信的片段部分,了解抽屉片段和活动是如何通信的


实际上,这个抽屉涉及的内容很多,但你应该能在一两天内很好地掌握它。

我想我知道该怎么做了。我原以为可以使用NavigationDrawer切换整个活动,但现在我知道了如何使用drawer菜单正确地交换片段。