Reputation: 1528
I have a Fragment A
which navigates to Fragment B
Fragment B
hosts a ViewPager2
.
ViewPager2
has two fragments inflated in it - Fragment C
and Fragment D
.
On clicking an item in Fragment C
I want to navigate to a new instance of Fragment D
on top of Fragment B
.
Currently, my code is something like this -
findNavController().navigate(
R.id.action_FragmentC_to_FragmentD,
bundleOf("id" to id, "type" to "list")
)
However, when I try to navigate I get the following exception -
java.lang.IllegalArgumentException: Navigation action/destination com.test.at:id/action_FragmentC_to_FragmentD cannot be found from the current destination Destination(com.krtkush.audiotime:id/FragmentB) label=FragmentB
From what I can understand is that the navigation component is still on Fragment B
but I'm trying to navigate to Fragment D
from Fragment C
and hence it is throwing an exception.
I (think) can fix this by adding a listener which informs Fragment B
when the item is tapped in Fragment C
and then navigate to Fragment D
from Fragment B
. However, this will make my Fragment C
tightly coupled to Fragment B
which I don't want to. Anyway to fix this is another way?
Upvotes: 8
Views: 1770
Reputation: 199825
If you do not navigate()
to Fragment C
and Fragment D
, you will remain on the last destination you navigated to: Fragment B
, that is the expected behavior. The NavController knows nothing about child fragments such as fragments within a ViewPager of Fragment B
and therefore you were never on Fragment C
as a destination.
If you never navigate()
to Fragment C
and it is only viewable as part of your ViewPager, then Fragment C
should not be in your graph. Any actions from fragments within Fragment B
's ViewPager should be actions on Fragment B
directly (the destination you're actually on).
Note that you can reuse the same actions names on fragments such as Fragment D
if you are also using them as standalone destinations in your graph (thus ensuring that the action is available in both cases).
Upvotes: 8