使用导航组件导航到首选项片段 [英] Navigating to preference fragment using navigation component
问题描述
我正在尝试将中型应用程序迁移到新的Android navigation
组件.
I'm trying to migrate my medium sized app to the new Android navigation
component.
当前,我的应用程序由single activity
组成,并且我打算将其保持不变(就此而言);因此,我面临着这个问题,其中有一个设置片段(PreferenceFragment
),基本上可以从其他所有片段中导航到该片段.
此导航是通过应用栏中的菜单进行的,因此onOptionsItemSelected
(包含此导航)位于主要活动中.
Currently, my app consists of the single activity
and I'm planning on keeping it the same (for that matter); So, I'm facing this issue in which I have a settings fragment (PreferenceFragment
) that can be navigated to, basically, from every other fragment.
This navigation is made through a menu in the app bar, therefore onOptionsItemSelected
(containing this navigation) is in the main activity.
我无法确定将settingsFragment
连接到其他模块的正确方法是什么.
对我来说,将它连接到所有其他对象似乎就像意大利面条.
I'm having trouble figuring what is the right way to connect the settingsFragment
to the other ones.
Connecting it to all others seems like spaghetti to me.
-
settingsFragment
应该连接到所有其他片段吗?
Should
settingsFragment
be connected to all another fragment?
我应该放弃单一活动应用程序架构,因为Google没有给出足够的理由(或任何理由)来支持它吗?
Should I abandon the single activity application architecture since Google isn't giving enough reasons (or any reasons) to support it?
推荐答案
要解决您的问题,可以使用global actions
.
要使用它们,您需要在<navigation>
标记内定义动作,而不是像通常那样在<fragment>
内定义动作.
您的导航图将包含下一个代码
To deal with your problem, you can use global actions
.
To use them you need to define action inside <navigation>
tag, not inside <fragment>
as you usually do.
Your nav graph will contain the next code
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!--Your other fragments-->
<!--Settings fragment-->
<fragment
android:id="@+id/settingsFragment"
android:name="com.example.oleksii.stackoverflow.SettingsFragment"/>
<!--Global action-->
<action android:id="@+id/open_settings_fragment"
app:destination="@id/settingsFragment"/>
</navigation>
在图形编辑器中,它将以另一种方式显示(仅在destination
左侧的箭头):
In the graph editor it will be displayed in the next way (just arrow in the left of destination
):
更多详细信息: https://developer.android.com/topic/libraries/architecture/navigation/navigation-global-action
这篇关于使用导航组件导航到首选项片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!