Michael Evans

A bunch of technobabble.

Hands on With ViewPager2

| Comments

Today Google released their alpha of ViewPager2, a signal of the nail in the coffin for the original ViewPager, originally released in 2011!

Since then, I think it’s safe to say that most developers have needed to make a ViewPager. Despite how prolific it is, it certainly isn’t the most straightforward widget to include. I think we all have at least once wondered whether we should use a FragmentPagerAdapter or a FragmentStatePagerAdapter. Or wondered if we can use a ViewPager without Fragments.

And API confusion aside, we’ve still had long standing, feature requests. RTL support? Vertical orientation? There are numerous open source solutions for these, but nothing official from the support library (now AndroidX)…until now!

Let’s dive in and try to set up ViewPager2! You’ll need your project configured with AndroidX already, as well as supporting minSdkVersion 14 or higher.

The first thing we’ll need to do is add the library to our build.gradle dependencies.

1
implementation 'androidx.viewpager2:viewpager2:1.0.0-alpha01'

If you’re familiar with RecyclerView, setting up ViewPager2 will be very familiar. We start off by creating an adapter:

1
2
3
4
5
6
7
8
9
10
11
class CheesePagerAdapter(private val cheeseStrings: Array<String>) : RecyclerView.Adapter<CheeseViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CheeseViewHolder {
        return CheeseViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.cheese_list_item, parent, false))
    }

    override fun onBindViewHolder(holder: CheeseViewHolder, position: Int) {
        holder.cheeseName.text = cheeseStrings[position]
    }

    override fun getItemCount() = cheeseStrings.size
}

and pair it with a RecyclerView.ViewHolder.

1
2
3
4
class CheeseViewHolder(view: View) : RecyclerView.ViewHolder(view) {

    val cheeseName: TextView = view.findViewById(R.id.cheese_name)
}

Finally, just like RecyclerView, we set the adapter of our ViewPager2 to be an instance of the RecyclerView adapter. However, you’ll note that there’s no need for a LayoutManager.

1
viewPager.adapter = CheesePagerAdapter(Cheeses.CheeseStrings)

And with that, we have a working ViewPager2!

We can even set the orientation to scroll vertically with just one line:

1
viewPager.orientation = ViewPager2.ORIENTATION_VERTICAL

Based on the release notes there are a lot of issues left to fix before this moves to a final release – but this is a long awaited update for one of those oldest support library components.

The sample code for this post can be found here. Thanks to Chris Banes’ CheeseSquare for the sample data for this demo!

Comments