当我使用提供 android studio 的 Activity 抽屉导航模板时,如何使用 Fragments 打开 Drawerlayout 上的项目?

How can I use Fragments to open items on a Drawerlayout, when i used the Activity Drawer Navigation Template that provides android studio?

提供Android工作室的模板

这就是我尝试做的。 R.id.x 是什么?我尝试在 xml ActivityMain 中使用布局 ID,但没有显示或覆盖 activity 信息的片段。

选择其中一项后,片段将显示在 activity 上方。 activity 有几个属于 material 设计的元素,如 FAB 或工具栏,这会给我的工作带来问题吗?

activity_main.xml 中尝试替换:

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

有了这个:

<FrameLayout android:id="@+id/fragment_container"
             android:layout_width="match_parent"
             android:layout_height="match_parent" />

然后使用 R.id.fragment_container 作为你的 R.id.x

然而,这将用 FAB 和协调器布局替换视图。但是您可能希望将它们添加到您想要的片段中。

如果不是,您可以尝试替换下面在 app_bar_main.xml 中找到的 xml 或将其包装在 FrameLayout.

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

更新:

activity_main.xml 中替换会导致一些问题,因为这会删除工具栏。

如果您替换 app_bar_main.xml 中的包含,您的片段很可能会与顶部的工具栏重叠。为防止出现这种情况,您可以尝试在上面的 FrameLayout 代码段中添加 app:layout_behavior="@string/appbar_scrolling_view_behavior"

R.id.x 是您的片段将被替换的视图的 ID。所以在你的布局中 R.layout.xyz 你已经创建了一个布局

<FrameLayout android:id="@+id/fragment_container"
             android:layout_width="match_parent"
             android:layout_height="match_parent" />

和 add/replace 该 ID 的片段。 (R.id.fragment_container) 这样您的新片段将放置在该布局中。

transaction.add(R.id.fragment_container, firstFragment)

最后使用他们提供给我的答案中的一些建议解决了问题。

  1. 更改content_main.xml内容。使用具有相应 ID 的 FrameLayout。

  1. 在 onNavigationItemSelected(MenuItem item) 上添加片段

  1. 结果

当我按下菜单项时...

...显示片段