Search code examples
androidandroid-jetpack-navigationandroid-viewpager2

Navigate from ViewPager2 to another fragment using jetpack


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?


Solution

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