Nowadays, using navigation component, we have complex apps which manipulate a bunch of fragments flows.
In my app, I have a simple activity with only a <androidx.fragment.app.FragmentContainerView with app:defaultNavHost="true"
Note: In this explanation, I will consider that FragmentContainerView == NavHostFragment
From inner fragments of this activity/main's NavHostFragment, I open sometimes DialogFragment using <dialog>
tag of my nav graph. This dialog is using his own NavHostFragment which open a bunch of fragments screen.
Using this representation (yeah 2 overlapping dialogs doesn't sounds good but it's real :p) :
Activity
---- NavHostFragment (id:1, tag:tag_1)
-------- FragmentA
-------- FragmentB
-------- DialogFragmentC (id: dialog_fragment_c)
------------- NavHostFragment (id:2, tag:tag_2)
------------------ FragmentD
------------------ FragmentE
-------- DialogFragmentF (id: dialog_fragment_f)
------------- NavHostFragment (id:3, tag:tag_3)
------------------ FragmentE
------------------ FragmentH
1°) How can I find DialogFragmentC from activity easily
with <dialog>
tag in nav graph we are not able to assign a fragment's tag to the supportFragmentManager like old method (show(supportFragmentManager, tagDialog))
perform a findFragmentByTag
For now, I'm using this piece of code:
From MainActivity:
val dialogFragmentC = (supportFragmentManager.findFragmentById(
R.id.activity_nav_host_fragment // NavHostFragment id of MainActivity
) as NavHostFragment).childFragmentManager.fragments.filterIsInstance<DialogFragmentC>().lastOrNull()
it sounds like an ugly code
2°) How can I find DialogFragmentC from FragmentD
From FragmentD:
2.1°) Like this, it doesn't work because NavHostFragment (id:2, tag:tag_2) is attached to activity'supportFragmentManager
requireParentFragment().parentFragment // returns null (requireParentFragment is NavHostFragment (id:2, tag:tag_2))
2.2°) because we know that this fragment is used only in 1 DialogFragment type class, we could use point 1°) to retrieve de DialogFragment
3°) How can I find DialogFragment's FragmentE
FragmentE is used in two different types of DialogFragment. I could expect to act differently depending on which one I'm in.
3.1°) I could perform point 1°) and check on multiple dialogs fragment opened which one has a navHostFragment that successfully match the parentFragment (NavHostFragment (id:2, tag:tag_2) or (id:3, tag:tag_3)) of FragmentE.
If anyone has an idea to simplify this way of doing
CodePudding user response: