简体   繁体   中英

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

Template that provide Android Studio

模板

This is how I try to do. What is the R.id.x?. I tried using layout id in xml ActivityMain but not the fragment is displayed or overlaid with out activity information.

添加片段

After selecting one of the items, the fragment will be displayed above the activity. The activity has several elements belonging to material design as the FAB or the Toolbar, Could this create problems with what I do?

导航抽屉

In activity_main.xml try replacing:

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

With this:

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

And then use R.id.fragment_container as your R.id.x .

This will however replace the view with the FAB and coordinator layout. But you will probably want to add them to the fragments where you want them.

If not you could try replacing the xml found below in app_bar_main.xml , or wrap it in the FrameLayout .

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

Update:

Replacing in activity_main.xml will cause some issues as that removes the toolbar.

If you replace the include in app_bar_main.xml your fragments will most likely get overlapped by the toolbar at the top. To prevent this you could try adding app:layout_behavior="@string/appbar_scrolling_view_behavior" in the FrameLayout snippet above.

R.id.x is the id of the View that your fragment going to be replaced. So in your layout R.layout.xyz you have created a layout

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

and add/replace the fragment to that id. (R.id.fragment_container) such that your new fragment will be placed in that layout.

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

At the end solved the problem using some of the recommendations made in the answers they provided me.

  1. Change content_main.xml content. Using a FrameLayout with its correspodiente id.

content_main.xml

  1. Add fragment on onNavigationItemSelected(MenuItem item)

添加片段

  1. Result

When I press a menu item ...

菜单

...the fragment is displayed

分段

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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