ViewPager2 in Android: Getting Started

In this tutorial for Android, you’ll learn to use the new ViewPager2 widget. Along the way you will build an app to show celebrity doppelganger animals. By Rajdeep Singh.

Leave a rating/review
Download materials
Save for later
Share

If you’ve used Android apps for some time, you’ve likely noticed many apps feature a common swipeable screen pattern. During the onboarding process, many apps use this pattern to showcase their major features one at a time. Another popular use case is using swipeable tabs to show different sections of the app.

Most developers use the ViewPager widget to develop these screens. On November 20, 2019, Google announced the stable version of ViewPager2, which replaces the old ViewPager and fixes many of its weaknesses.

In this tutorial, you’ll build Animal Doppleganger, an app that shows celebrity doppelganger animals, and learn:

  • How ViewPager2 works and how it differs from the previous ViewPager.
  • How to use ViewPager2 with Fragments.
  • What goes on under the hood of FragmentStateAdapter, a replacement for FragmentStatePagerAdapter.
  • How to implement vertical swiping with ViewPager2.
Note: This tutorial assumes you have previous experience developing for Android in Kotlin. If you’re unfamiliar with Kotlin, take a look at this tutorial. If you’re also new to Android development, check out the Getting Started with Android tutorials.

Getting Started

Click the Download Materials button at the top or bottom of the page to download the starter and final projects.

Now, open Android Studio and click Open an existing Android Studio project.

Android Studio start new project wizard

Navigate to the starter project directory you downloaded and click Open.

Starter project selected new project wizard

Take some time to familiarize yourself with the code.

Project Structure

You’ll find the following files in the starter project:

  • MainActivity.kt is the main class for this tutorial. You’ll add ViewPager2 related code primarily in this class.
  • DoppelgangerFragment.kt is a class you’ll use to add doppelganger images in your app. It extends Fragment and shows different images based on the value passed in its getInstance(position: Int) method.
  • A directory named doppelgangers inside the assets directory holds six photos named 0 to 5 with the .jpg extension.

Now that you have an overview of the files in this project, build and run the app. You’ll see a screen like this:

Animal doppelganger begin project files

Introducing ViewPager2

Google announced ViewPager2 around Google IO/19 as the successor to the existing ViewPager. As of November 2019, a stable version of ViewPager2 is finally available. To start using this new component, you have to migrate to AndroidX, as it’s not available in the support library.

According to the official Google documentation, ViewPager2 is addressing most of its predecessor’s shortcomings, including right-to-left layout support, vertical orientation and modifiable Fragment collections. You’ll explore many of these features while working on the sample project.

What’s New Since ViewPager

Your app’s users may not notice much change apart from the smoother performance, but, as an app developer, you should notice many improvements.

ViewPager2 uses RecyclerView, one of the most used widgets in the Android world, to show collections of items. This is a huge change for the ViewPager API, as RecyclerView is a powerful and robust widget.

Using all of RecyclerView’s benefits, ViewPager 2 provides these improvements:

  • It supports vertical paging by using LinearLayoutManager. This means you can easily switch between horizontal and vertical orientations.
  • It provides support for right-to-left, or RTL, layouts.
  • It supports the use of a DiffUtil by default, since it’s a RecyclerView. This lets you dynamically add Fragments or Views and then notify the ViewPager2 to update the UI.

Enough with the theory, time to start coding!

Implementing a Basic Swipeable Screen

In this section, you’ll modify the starter project to show swipeable sections of animal doppelgangers instead of showing only Doguel Jackson.

This requires the following:

  1. Adding the dependency for androidx.viewpager2:viewpager2 in the app level build.gradle.
  2. Adding the ViewPager2 XML widget in the layout file.
  3. Wiring the ViewPager2 with custom FragmentStateAdapter.

Adding the ViewPager2 Widget

In the starter project, select the Android view of the project files if not already selected.

Android project mode selection opened in Android Studio

Now, open build.gradle (Module: app) and add the following below the line marking TODO:1:

implementation 'androidx.viewpager2:viewpager2:1.0.0'

The code above tells Gradle that your app module depends on androidx.viewpager2:viewpager2. With the line added, sync Gradle by clicking the Sync Now button that shows up at the top of the file. After a successful sync, you can start using ViewPager2 in the project!

Right now, the app shows a single Fragment in MainActivity. It showcases my all-time favorite Avenger, Doguel Jackson.

Before you can display other famous doppelgangers, you need to remove some existing code. Open MainActivity.kt and remove the following code:

supportFragmentManager.beginTransaction()
        .add(R.id.fragmentContainer, DoppelgangerFragment.getInstance(0)).commit()

Now, open activity_main.xml, which is the layout file of MainActivity, and remove this code snippet:

<FrameLayout
  android:id="@+id/fragmentContainer"
  android:layout_width="match_parent"
  android:layout_height="match_parent" />

This Framelayout contained a single instance of the Fragment, but you’ll want to show multiple ones instead!

Build and run the app to make sure you see a blank screen like this:

Android emulator showing empty app screen

If your app screen looks as blank as one’s mind tends to be during an important exam, you can start adding the ViewPager2 related code. With activity_main.xml still open, add the following lines below TODO:2:

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

This adds a ViewPager2 widget in your layout with the ID doppelgangerViewPager. You’ll use it to refer to this view in your Kotlin code. This view covers the entire screen because of the match_parent value for both layout_width and layout_height.

You won’t see any change if you try to run the app at this point because ViewPager2 on its own is simply a ViewGroup. The magic happens when you add a data adapter to it, which you’ll do in the next section.

Wiring Your ViewPager2 With a FragmentStateAdapter

In this section, you’ll create a custom FragmentStateAdapter and wire it with your ViewPager2 widget. You’ll learn more about how exactly FragmentStateAdapter works later.

Create a new Kotlin file and name it DoppelgangerAdapter. Paste the following code inside:

import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter

class DoppelgangerAdapter(activity: AppCompatActivity, val itemsCount: Int) :
    FragmentStateAdapter(activity) {

  override fun getItemCount(): Int {
    return itemsCount
  }

  override fun createFragment(position: Int): Fragment {
    return DoppelgangerFragment.getInstance(position)
  }
}

Here’s a breakdown of the code:

  • You declare a class named DoppelgangerAdapter which takes two parameters. The first is a reference to the Activity which hosts the adapter, and the second is an Int that tells the adapter the number of items it’ll show. The Activity reference is passed to the super constructor. You’ll see why this is required later.
  • Next, you override getItemCount() which is an abstract method that returns the total number of items in the adapter.
  • Finally, you override createFragment(position: Int), which is again an abstract method and returns a Fragment instance for the given position. DoppelgangerFragment.getInstance(position) creates instances of DoppelgangerFragment with a different doppelganger picture for different values of position.

Here comes the last step before your ViewPager2 starts working. Go to MainActivity.kt and add the following import statement:

import kotlinx.android.synthetic.main.activity_main.*

Then, add the following lines below TODO:3:

val doppelgangerAdapter = DoppelgangerAdapter(this, doppelgangerNamesArray.size)
doppelgangerViewPager.adapter = doppelgangerAdapter

In the code above, you created an instance of your DoppelgangerAdapter, passing in the current instance of MainActivity and the size of doppelgangerNamesArray, which is the number of pages you want to show.

MainActivity already had doppelgangerNamesArray defined, which is an array of strings containing the names of celebrities. It gets the value from strings.xml in res/values.

Give yourself a pat on the back!

Build and run the app and you’ll see Doguel Jackson again. But if you swipe, you’ll see other doppelgangers, too. The app should behave like this:

Animal doppelganger ViewPager screen being swiped right to left