Navigate from ViewPager2 to another fragment using jetpack

Viewed 1935

I have single activity, FragmentHome contains viewpager2. Inside of viewpager there is FirstFragment.

enter image description here

when I want to navigate from FirstFragment to SecondFragment which is not in viewpager2

enter image description here

it throws

 java.lang.IllegalArgumentException: navigation destination com.example.mymessangerfcm:id/action_FirstFragment_to_SecondFragment is unknown to this NavController

Dear community how to handle such navigation, and why the exception is thrown?

2 Answers

you should use the Global Action. When you are inside the viewpager, actually you are in a different navigation. So, you should make your action as Global. You can check the Global Action from official website :

https://developer.android.com/guide/navigation/navigation-global-action

After the making action as global, you can navigate like this;

findNavController().navigate(R.id.action_global_FirstFragment_to_SecondFragment)

Note: If you don't see global action after the doing it, rebuild your project.

I got below IllegalStateException when calling Navigation.findNavController(view) with ViewPager2. However, the same setup working fine with old ViewPager.

    java.lang.IllegalStateException: View android.widget.LinearLayout does not have a NavController set
Related