繁体   English   中英

当我使用提供Android Studio的活动抽屉导航模板时,如何使用片段在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 Studio的模板

模板

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

添加片段

选择其中一项后,片段将显示在活动上方。 该活动有几个属于材料设计的元素,例如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的include, app_bar_main.xml片段很可能会被顶部的工具栏重叠。 为防止这种情况,您可以尝试在上面的FrameLayout代码段中添加app:layout_behavior="@string/appbar_scrolling_view_behavior"

R.id.x是要替换您的片段的View的ID。 因此,在布局R.layout.xyz中,您已经创建了一个布局

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

并将片段添加/替换为该ID。 (R.id.fragment_container),以便将新片段放置在该布局中。

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

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

  1. 更改content_main.xml的内容。 使用带有其对应ID的FrameLayout。

content_main.xml

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

添加片段

  1. 结果

当我按下菜单项时...

菜单

...显示片段

分段

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM