简体   繁体   English

创建一个导航抽屉以链接到片段和活动

[英]Create a Navigation drawer to link to fragments and activities

So i have a navigation drawer like so it has 3 buttons that go to 2 different fragments and the other button which goes to an Activity.所以我有一个导航抽屉,所以它有 3 个按钮,可以转到 2 个不同的片段,另一个按钮可以转到 Activity。

样本

When I click one frag 1 my fragment opens up with the drawer still intact same goes for Frag 2 but when i click on the Activity 1 the Drawer disappears but i would like the drawer to continue in the activity as well.当我点击一个片段 1 时,我的片段打开,抽屉仍然完好无损,片段 2 也是如此,但是当我点击活动 1 时,抽屉消失了,但我希望抽屉也继续进行活动。 can this be done.可以这样做吗。

What you'd want to do (roughly) is你想要做的(大致)是

  1. Establish a menu as one of your resources and establish the items in that list.建立一个菜单作为您的资源之一,并在该列表中建立项目。
  2. In the activity that you want to contain the drawer, create the drawer object and create a callback for the onMenuItemSelected.在要包含抽屉的活动中,创建抽屉对象并为 onMenuItemSelected 创建回调。
  3. In that callback, reference the menu item ids you created before and use intents and fragment managers to either start the activity or fragment that you want based on what they select.在该回调中,引用您之前创建的菜单项 ID,并使用意图和片段管理器根据他们选择的内容启动您想要的活动或片段。

This can't be done.这是做不到的。

The DrawerLayout lives within your Activity and the Fragments that you switch to also live within the same Activity . DrawerLayout位于您的Activity ,您切换到的Fragments也位于同一个Activity This is the reason why switching fragments will leave the drawer intact.这就是为什么切换碎片会使抽屉完好无损的原因。 It's because they both exist within the same Activity without any interference.这是因为它们都存在于同一个 Activity 中,没有任何干扰。

However, launching an Activity is different.但是,启动Activity是不同的。 This is a completely different Activity which has it's own layout.这是一个完全不同的Activity ,它有自己的布局。

You actually only have two options if you wish to continue using a Drawer for main navigation.如果您希望继续使用抽屉进行主导航,您实际上只有两个选择。

  1. Remove the need for the second Activity and change that to a Fragment .不再需要第二个Activity并将其更改为Fragment This way, all your fragments will exist within the same parent Activity so it'll use the same drawer that exists in that parent Activity.这样,您的所有片段都将存在于同一个父Activity因此它将使用该父 Activity 中存在的相同抽屉。

  2. Create an identical DrawerLayout and NavigationView in the second Activity.在第二个活动中创建相同的DrawerLayoutNavigationView Call code to have the Drawer be opened when it's created.调用代码以在创建抽屉时打开它。 This way, although you're not really using the same Drawer, you're giving the illusion that it's still the same Drawer.这样,虽然您并没有真正使用同一个 Drawer,但您会产生它仍然是同一个 Drawer 的错觉。

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

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