Implement TabLayout with ViewPager in Android Jetpack Compose
How we can use pager with tabs to slide between pages with a smooth animation and a good infinite looping effect.
Introduction
Slide between pages are common with UIs like onboarding, setup wizards… I think you’ve already know how to do page slide by using ViewPager
. In case you are looking for a replacement of ViewPager
in Compose, I suggest you to look at this Pager
library.
This library is currently experimental. All of the APIs are flagged as an @ExperimentalPagerApi
, but it handles the core pager functionality very well.
In this post let’s check how we can use pager with tabs to slide between pages with a smooth animation and a good infinite looping effect.
Let’s begin! 🥰
Step1: Project Setup
First, please check the Pager website to get the latest version.
And then add the below to your app’s build.gradle
:
dependencies {
implementation "com.google.accompanist:accompanist-pager:0.12.0"
}
Step2: HorizontalPager
To implement tabs we will be using two components that are HorizontalPager
and PagerState
.
HorizontalPager
is a ViewPager in compose environment, allows user to horizontally swipe between pages. It is unnecessary to create all the pages at once because doing this would use a lot of memory and user would never swipe through all the pages. By default, HorizontalPager
only creates the current page as well as the off-screen pages to the left and to the right of the current page. Pages beyond this limit will be removed.
What is the solution of this problem?
Yeah there is: PagerState
This is a state of HorizontalPager
that we want to keep across compositions. Let’s have a look at the method signature of PagerState
: