ViewPager2 in Android with Example
Last Updated :
15 May, 2021
Before going to Viewpager2 let us know about Viewpager. Most of you have used WhatsApp, when you open WhatsApp you can see at the top, there are four sections Camera, Chats, Status, Calls these are the Viewpager. So a Viewpager is an android widget that is used to navigate from one page to another page by swiping left or right using the same activity. So when we use Viewpager, we can add different layouts in one activity and this can be done by using the fragments. Famous applications like WhatsApp, Snapchat uses Viewpager.
Viewpager2 is an updated or enhanced version of Viewpager released by Google on 7th Feb 2009. It comes with a variety of new features. The most important feature of viewpager2 that is not present in Viewpager is, the Recyclerview which makes Viewpager2 more efficient than Viewpager. By using the Recyclerview, we can add items dynamically. If you know how to implement a RecyclerView then you can easily implement ViewPager2.
Features of ViewPager2
- It uses Recyclerview implicitly and is the most important feature.
- Supports Right to Left layout.
- Supports Vertical orientation.
- CompositePageTransformer is introduced to combine multiple page transformers
- notifyDataSetChanged() fully functional.
More About ViewPager2
- View Group: Just like ViewPager the ViewPager2 extends from the ViewGroup. A ViewGroup is a view that can contain other views. It is a subclass of the View class. It is the base class for the layouts, like LinearLayout, RelativeLayout, etc.
- LayoutManager: The LayoutManager is the same that you have been used in RecyclerView. The LayoutManager is managed by the Viewpager and it manages the views and is used to set the orientation of the ViewPager2.
- RecyclerView: The Recyclerview is used to handle to components provided to it. It will show the data to the user that is assigned to it and makes ViewPager2 more efficient.
Page Change Callback Methods
- onPageScrolled(): This method is triggered when there is any scrolling activity for the current page.
- onPageSelected(): triggered when you select a new page.
- onPageScrollStateChanged(): triggered when there is scroll state will be changed.
Setting Orientation
By default the orientation of viewpager2 is Horizontal. We can set the orientation of viewpager2 to Vertical by calling the setOrientation() method and passing ORIENTATION_VERTICAL to it. For Horizontal Orientation use
YourViewPager2Object.orientation = ViewPager2.ORIENTATION_VERTICAL
Let’s now see how to use ViewPager2 in our project
To use ViewPager2, you have to first add the dependency in your Build.gradle file:
To do this. Go to app > Gradle Scripts > build.gradle (Module: app) and then write the following dependency ” implementation ‘androidx.viewpager2:viewpager2:1.0.0’ ” into dependencies section as shown below and then click on Sync now.
dependencies {
implementation 'androidx.viewpager2:viewpager2:1.0.0'
}
After doing all these steps let’s now build an application. So we are going to build the below application.
Step 1: Create a New Project
On the Welcome screen of Android Studio, click on Create New Project. If you have a project already opened, Go to File > New > New Project. Select a Project Template window, select Empty Activity and click Next. Enter your App Name in the Name field. Select Java from the Language drop-down menu.
Step 2: Add Vector Assets to show on the screen
Go to the app > res > drawable > right-click > new > Vector Asset and select any vector asset of your choice
Step 3: Go to activity_main.xml and add the ViewPager2 widget to it
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< LinearLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< androidx.viewpager2.widget.ViewPager2
android:id = "@+id/viewpager"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical" />
</ LinearLayout >
|
Step 4: Create a new Layout Resource file
Go to app > res > layout > right-click > New > Layout Resource File and name that file as “images_holder.xml”. Inside that file insert an ImageView widget and provide an id to it. This layout file will hold our images. Below is the code for the images_holder.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< LinearLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent" >
< ImageView
android:id = "@+id/images"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</ LinearLayout >
|
Step 5: Create an Adapter class
Go to the app > java > right click on first package name > new > java class name that class as ViewPager2Adapter. An adapter is an important class to work with Recyclerview. Because it contains all the important methods dealing with RecyclerView. Below is the implementation of the Adapter class. For better understanding comments are added inside the code. Below is the code for the ViewPager2Adapter.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
class ViewPager2Adapter extends RecyclerView.Adapter<ViewPager2Adapter.ViewHolder> {
private int [] images = {R.drawable.ic_baseline_looks_one_24, R.drawable.ic_baseline_looks_two_24, R.drawable.ic_baseline_looks_3_24,
R.drawable.ic_baseline_looks_4_24, R.drawable.ic_baseline_looks_5_24};
private Context ctx;
ViewPager2Adapter(Context ctx) {
this .ctx = ctx;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(ctx).inflate(R.layout.images_holder, parent, false );
return new ViewHolder(view);
}
@Override
public void onBindViewHolder( @NonNull ViewHolder holder, int position) {
holder.images.setImageResource(images[position]);
}
@Override
public int getItemCount() {
return images.length;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
ImageView images;
public ViewHolder( @NonNull View itemView) {
super (itemView);
images = itemView.findViewById(R.id.images);
}
}
}
|
Step 6: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
public class MainActivity extends AppCompatActivity {
private ViewPager2 viewPager2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager2 = findViewById(R.id.viewpager);
ViewPager2Adapter viewPager2Adapter = new ViewPager2Adapter( this );
viewPager2.setAdapter(viewPager2Adapter);
viewPager2.registerOnPageChangeCallback( new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled( int position, float positionOffset, int positionOffsetPixels) {
super .onPageScrolled(position, positionOffset, positionOffsetPixels);
}
@Override
public void onPageSelected( int position) {
super .onPageSelected(position);
}
@Override
public void onPageScrollStateChanged( int state) {
super .onPageScrollStateChanged(state);
}
});
}
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...