Navigating to preference fragment using navigation component

大兔子大兔子 提交于 2019-12-08 15:30:23

问题


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.

  1. Should settingsFragment be connected to all another fragment?

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!