Android ViewPager2

Filed Under: Android

It’s been hardly a week since Google has released the new ViewPager2’s alpha version. We’re here with our very own introduction to ViewPager2 through a sample Android Application.

ViewPager has been an important component of the UI since a long while. Still, it always gives chills to developers when they try to implement certain features. Features such as updating Fragment content, swiping right to left and swiping vertical require a lot of effort.

Things like these have brought ViewPager2 into the scene. Let’s see what it has in store for us.

Android ViewPager2

In order to use ViewPager2 in your application add the following dependency in the build.gradle.


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

Android ViewPager2 Features

Following are the features that ViewPager2 brings to the table:

  • Right to Left Layout Support
  • Vertical Orientation
  • Use of RecyclerView implicitly
  • Shift from PagerAdapter to RecyclerView.Adapter
  • Better control of Animation on Page change thanks to RecyclerView
  • A Smarter Page Change Listener
  • A working notifyDataSetChanged

In order to add ViewPager2 in your layout add the following snippet:


<androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
In the older ViewPager’s addOnPageChangeListener method callback interface, OnPageChangeListener, we had to override all three methods. In ViewPager2 it is no longer necessary, thus preventing boilerplate code.

If you check the implementation of ViewPager2, it uses RecyclerView within. Thus if you’ve implemented RecyclerView, implementing ViewPager2 wouldn’t be much different.

You can use fragments inside ViewPager2 as well as we did in ViewPager.

You just need to use FragmentStateAdapter instead of FragmentStatePagerAdapter.

In order to register a Listener on ViewPager2, we need to do the following:


viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }
        });

Note: You can override either or all of the methods of the callback.

In the following section, we’ll be implementing ViewPager2 using the RecyclerView.Adapter pattern.
Implementation using FragmentStateAdapter is similar to what we did in ViewPager 1

Android ViewPager2 Example Project Structure

Android Viewpager2 Project Structure

Android Viewpager2 Example Project Structure

Code

Coming to the code, we’ve used androidx packaging system.

The code for the activity_main.xml file is given below:


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

</androidx.constraintlayout.widget.ConstraintLayout>

The code for the MainActivity.java class is given below:


package com.journaldev.androidviewpager2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    ViewPager2 viewPager2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager2 = findViewById(R.id.viewPager2);

        List<String> list = new ArrayList<>();
        list.add("First Screen");
        list.add("Second Screen");
        list.add("Third Screen");
        list.add("Fourth Screen");

        viewPager2.setAdapter(new ViewPagerAdapter(this, list, viewPager2));

    }
}

Let’s look at the layout for each of the viewpager screens:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textColor="@android:color/white"
        android:textSize="32sp"
        tools:text="item" />


    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnToggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Toggle Orientation" />

</RelativeLayout>

The code for the ViewPagerAdapter.java class is given below:


package com.journaldev.androidviewpager2;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewHolder> {

    private List<String> mData;
    private LayoutInflater mInflater;
    private ViewPager2 viewPager2;


    private int[] colorArray = new int[]{android.R.color.black, android.R.color.holo_blue_dark, android.R.color.holo_green_dark, android.R.color.holo_red_dark};

    ViewPagerAdapter(Context context, List<String> data, ViewPager2 viewPager2) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
        this.viewPager2 = viewPager2;
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.item_viewpager, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String animal = mData.get(position);
        holder.myTextView.setText(animal);
        holder.relativeLayout.setBackgroundResource(colorArray[position]);
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }


    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView myTextView;
        RelativeLayout relativeLayout;
        Button button;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.tvTitle);
            relativeLayout = itemView.findViewById(R.id.container);
            button = itemView.findViewById(R.id.btnToggle);

            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                    if(viewPager2.getOrientation() == ViewPager2.ORIENTATION_VERTICAL)
                    viewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
                    else{
                        viewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
                    }
                }
            });
        }
    }

}

In the above code, we’ve passed the ViewPager2 instance to demonstrate the orientation toggle. On the button click, we change the orientation of the ViewPager2.

The output of the above application in action is given below:

Android Viewpager2 Output

Android Viewpager2 Example App

ViewPager2 has just been released and few known issues such as clipToPadding have been reported. We predict a stable version of ViewPager2 to be out with Android Q this year.

To know the other main issues, visit this link.

That brings an end to this tutorial. You can download the project from the link below:

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages