Home > front end >  NavHostFragment and ViewPager2 doesn't work at the same time
NavHostFragment and ViewPager2 doesn't work at the same time

Time:10-25

I have an app, that has a few fragments in it. I'm using ViewPager 2 to swipe between them.

Lately I've added Navigation component to make a way to get into one specific fragment that is not avilable for user just by swipe.

I've found out, that whever I place FragmentContainerView over the ViewPager2 in my MainActivity layout, I can go to this unvailable fragment, but I can't swipe. Same thing whener I switch FragmentContainerView with ViewPager2. Is there any way to make them both work at the same time?

Here's my layout

  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    
    <androidx.fragment.app.FragmentContainerView
        android:id="@ id/fragmentContainerView"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph" />
    <androidx.viewpager2.widget.ViewPager2
        android:id="@ id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

CodePudding user response:

They can work together but not like this, at least not for what you want.

Navigation component is made to handle traveling between destinations. ViewPager2 is a widget to be used in a destination, not for traveling between them.

For what you are describing you will need to have FragmentA that will contain ViewPager2 where all of the swiping will take place and handling of fragments (let's say Fragment1, Fragment2, Fragment3) in the ViewPager2.

Those fragments will have nothing to do with the Navigation component.

Navigation component will come to play when you will want to go from FragmentA to FragmentB.

  • Related