Search code examples
androidandroid-viewpager2

How to navigate from FragmentA to FragmentB in viewPager from FragmentA class?


I have a viewPager in MainActivity and have 2 fragments FragmentOne and FragmentTwo. In my FragmentOne I have a button that suppose to redirect user and open FragmentTwo. I know how to make it from parent MainActivity. But the trigger happens in FragmentOne. So how to achieve that directly from FragmentOne to FragmentTwo?


Solution

  • add a public function in MainActivity that navigate from FragmentOne to FragmentTwo then get MainActivity in FragmentOne and call that function, so your code in FragmentOne should look like this:

    (requireActivity() as AuthActivity).navigateFromFragmentAToFragmentB()
    

    And in your activity you need to create that public function named navigateFromFragmentAToFragmentB that will navigate from FragmentOne to FragmentTwo