问题
I'm trying to migrate my medium sized app to the new Android navigation
component.
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.
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.
Should
settingsFragment
be connected to all another fragment?Should I abandon the single activity application architecture since Google isn't giving enough reasons (or any reasons) to support it?
回答1:
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>
In the graph editor it will be displayed in the next way (just arrow in the left of destination
):
More details: https://developer.android.com/topic/libraries/architecture/navigation/navigation-global-action
回答2:
but if your preferences are hierarchical you get Fragment <insert fragment name here> declared target fragment <guid> that does not belong to this FragmentManager!
when you click on a child preference.
i have not found a solution to this yet.
来源:https://stackoverflow.com/questions/53029821/navigating-to-preference-fragment-using-navigation-component