ViewPager Tutorial: Getting Started in Kotlin

In this ViewPager tutorial for Android, you’ll learn how to use a ViewPager to navigate between content pages in Kotlin. By Diana Pislaru.

Leave a rating/review
Save for later
Share

In this tutorial, you’ll become familiar with the ViewPager by modifying an existing app to make the UI more enjoyable. Along the way, you’ll also learn:

  • How the ViewPager works
  • How to keep it memory-efficient
  • How to add some nice features to your ViewPager

Note: This tutorial assumes you have previous experience with developing for Android in Kotlin. If you are unfamiliar with the language have a look at this tutorial. If you’re beginning with Android, check out some of our Getting Started and other Android tutorials.

Note: This tutorial assumes you have previous experience with developing for Android in Kotlin. If you are unfamiliar with the language have a look at this tutorial. If you’re beginning with Android, check out some of our Getting Started and other Android tutorials.

Getting Started

Download the starter project and open it by starting Android Studio and selecting Open an existing Android Studio project:

Open an existing Android Studio project

Navigate to the sample project directory and click Open.

select the project

Take a look at the existing code before going on with the tutorial. Inside the assets directory, there is a JSON file containing some information about the top 5 most popular Android related movies ever made. :]

You can find the helper methods used to read the JSON data inside MovieHelper.kt. The Picasso library helps to easily download and display the images on the screen.

This tutorial uses fragments. If you are not familiar with fragments have a look at this tutorial

Build and Run the project.

Running Starter Project

The app consists of a few pages, each displaying some information about a movie. I bet the first thing you tried to do was swipe left to check out next movie! Or was it just me? For now, you can not-so-gracefully navigate between pages using the Previous and Next buttons at the bottom of the screen.

Introducing the ViewPager

Adding a ViewPager to the UI will allow the users to move forward or backward through the movies by swiping across the screen. You don’t have to deal with the slide animation and the swipe gesture detection, so the implementation is easier than you might think.

You’ll divide the ViewPager implementation into three parts:

  • Adding the ViewPager
  • Creating an Adapter for the ViewPager
  • Wiring up the ViewPager and the Adapter

Preparing the ViewPager

For step one, open MainActivity.kt and remove everything inside onCreate(), below this line:

val movies = MovieHelper.getMoviesFromJson("movies.json", this)

Remove the replaceFragment() method from the bottom of the class as well.

Now open activity_main.xml and replace everything inside the RelativeLayout with the following:

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_height="match_parent"
    android:layout_width="match_parent" />

Here you created the ViewPager view, which is now the only child of the RelativeLayout. Here’s how the xml file should look:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_height="match_parent"
                android:layout_width="match_parent"
                tools:context="com.raywenderlich.favoritemovies.MainActivity">

  <android.support.v4.view.ViewPager
      android:id="@+id/viewPager"
      android:layout_height="match_parent"
      android:layout_width="match_parent" />

</RelativeLayout>

ViewPager is only available through the Android Support Library. The Android Support Library is actually a set of libraries that provide backward compatible implementations of widgets and other standard Android functionality. These libraries provide a common API that often allow the use of newer Android SDK features on devices that only support lower API levels. You should familiarize yourself with the Support Library and Support Library Packages.

Go back to MainActivity.kt and first import the ViewPager to be able to use it with this line:

import android.support.v4.view.ViewPager

Now you can add the following line at the top of the class to declare the ViewPager:

private lateinit var viewPager: ViewPager

Note: Use the keyword lateinit to avoid making the view nullable if you want to initialize it later. Read more about lateinit and other Kotlin modifiers here.

Note: Use the keyword lateinit to avoid making the view nullable if you want to initialize it later. Read more about lateinit and other Kotlin modifiers here.

Add this line at the bottom of the onCreate() method to link your ViewPager reference to the xml view you created previously:

viewPager = findViewById(R.id.viewPager)

Implementing the PagerAdapter

Step one completed! You now have a ViewPager that doesn’t do anything particularly interesting without an Adapter that tells it what to display. If you run the app now you won’t be able to see any movies:

Empty Screen

The ViewPager usually displays the “pages” using fragment instances, but it can also work with simple views such as ImageView if you want to display static content. In this project, you will display multiple things on each page. Fragments are here to help you.

You will connect your Fragment instances with the ViewPager using a PagerAdapter, which is an object that sits between the ViewPager and the data set containing the information you want the ViewPager to display (in this case the movies array). The PagerAdapter will create each Fragment, add the corresponding movie data to it and return it to the ViewPager.

PagerAdapter is an abstract class, so you will have an instance of one of its subclasses (FragmentPagerAdapter and FragmentStatePagerAdapter) rather than an instance of the PagerAdapter itself.

FragmentPagerAdapter or FragmentStatePagerAdapter?

There are two types of standard PagerAdapters that manage the lifecycle of each fragment: FragmentPagerAdapter and FragmentStatePagerAdapter. Both of them work well with fragments, but they are better suited for different scenarios:

  • The FragmentPagerAdapter stores the fragments in memory as long as the user can navigate between them. When a fragment is not visible, the PagerAdapter will detach it, but not destroy it, so the fragment instance remains alive in the FragmentManager. It will release it from memory only when the Activity shuts down. This can make the transition between pages fast and smooth, but it could cause memory issues in your app if you need many fragments.
  • The FragmentStatePagerAdapter makes sure to destroy all the fragments the user does not see and only keep their saved states in the FragmentManager, hence the name. When the user navigates back to a fragment, it will restore it using the saved state. This PagerAdapter requires much less memory, but the process of switching between pages can be slower.

It’s time to decide. Your list of movies has only five items, so the FragmentPagerAdapter might work after all. But what if you get bored after this tutorial and watch all Harry Potter movies? You’ll have to add 8 more items to the JSON file. What if you then decide to add your favorite TV series as well? That array can become pretty large. In this case, the FragmentStatePagerAdapter works better.

Diana Pislaru

Contributors

Diana Pislaru

Author

Jason Donmoyer

Tech Editor

Odie Edo-Osagie

Final Pass Editor

Joe Howard

Team Lead

Over 300 content creators. Join our team.