Create swipe views with tabs using ViewPager 2

Tram Ho

overview

Swipe views allow us to navigate screens such as tabs, with horizontal finger gestures or swiping. This type of navigation is also known as horizontal pagination.

Setup

You can create swipe views using ViewPager2 in AndroidX. To use ViewPager2 and tabs, you need to add ViewPager2 in Material Component to your project. To set up your layout with ViewPager2, add the <ViewPager2> element to your XML layout. For example, if each page in swipe views is displayed entirely with the parent layout, your layout should look like this:

To insert sub views for each page, you need to link this layout to the FragmentStateAdapter. Here’s how you can use it to swipe through Fragment objects:

The following sections show how you can add tabs to help navigate between pages.

Add tabs with TabLayout

TabLayout provides a way to display tabs horizontally. When used in conjunction with ViewPager2, TabLayout can provide a familiar interface for navigating between pages in swipe mode. Figure 1: A TabLayout has four tabs. To include a TabLayout in ViewPager2, add the <TabLayout> element above the <ViewPager2> element, as shown below:

Next, create a TabLayoutMediator to link TabLayout with ViewPager2 and attach the following:

Thank you for reading my translation. Source: https://developer.android.com/guide/navigation/navigation-swipe-view-2

Share the news now

Source : Viblo