Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PagerTabStrip with ViewPager2

I want to use ViewPager2 because it is supposed to replace ViewPager and I hope to get rid of some problems I've had with ViewPager.

I want to do this:

<androidx.viewpager2.widget.ViewPager2
    android:id="@+id/detail_pager_view"
    android:layout_height="match_parent"
    android:layout_width="match_parent" >

    <androidx.viewpager.widget.PagerTabStrip
        android:id="@+id/detail_pager_strip"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_width="match_parent" />

</androidx.viewpager2.widget.ViewPager2>

But ViewPager2 complains that it cannot have any children. On the other hand, if I move PagerTabStrip out of ViewPager2 it complains that it must be a child of a ViewPager.

So it seems that PagerTabStrip is not compatible with ViewPager2. Am I correct?

Is there any current solution to this? (except writing your own PagerTabStrip)

like image 561
Andreas Jarl Avatar asked Nov 27 '19 08:11

Andreas Jarl


People also ask

What is difference between ViewPager and ViewPager2?

ViewPager2 is an improved version of the ViewPager library that offers enhanced functionality and addresses common difficulties when using ViewPager . ViewPager2 has several advantages such as vertical orientation support, RTL and access to DiffUtil .


1 Answers

Refering to this, you need to use TabLayout

Use of ViewPager2 in Android

<com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
</com.google.android.material.appbar.AppBarLayout>

<androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewpager"
        app:layout_anchor="@id/tabs"
        app:layout_anchorGravity="bottom"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
/>

like image 170
Gilberto Ibarra Avatar answered Oct 24 '22 02:10

Gilberto Ibarra