簡體   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