Android

Working with ViewPager2

Pinterest LinkedIn Tumblr

Nowadays, You’ve noticed that many apps are using SwipeView patterns. Actually, they want to show off the major functionality of the app. For that, we use viewpager2. Using all of RecyclerView benefits, ViewPager2 provides the below improvements

  • It supports vertical and horizontal orientation by using LinearLayoutManager. this means, that if you have a RecyclerView adapter, then you can use ViewPager2. No need to create a separate adapter for ViewPager2.
  • It provides support for RTL or LTR layouts.
  • You can dynamically add fragments and views and then notify ViewPager2 to update the UI because it supports the DiffUtil.

I don’t want to put back you in history that what is the difference between ViewPager and viewpager2? Let’s start to learn ViewPager2.

Android ViewPager2 Example

1- Open the Android Studio and create a new project.

2- To get the support of ViewPager2 in the project, we will add a ViewPager2 dependency. Open the build.gradle.xml file and add the below dependency.

dependencies {
    implementation "androidx.viewpager2:viewpager2:1.0.0"
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

3- Navigate to res=>values and open the strings.xml file and add the below strings line that has been used in this demo.

<resources>
    <string name="app_name">ViewPager2Example</string>

    <!-- App strings -->
    <string name="str_demo_tv">Start to invest</string>
    <string name="str_demo_tv_1">for your future!</string>
    <string name="str_demo_tv_2">Ex totam praesentium incidunt aut.</string>

    <string name="str_demo_tv_3">Follow our tips</string>
    <string name="str_demo_tv_4">to achieve success!</string>

    <string name="str_demo_tv_5">Keep your</string>
    <string name="str_demo_tv_6">investment safe</string>
    <string name="tv_skip">Skip</string>
</resources>

4- Go to res=>values and open the colors.xml file and add the below color lines that have been used in the demo.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
    <color name="color_status_bar">#212121</color>

    <!-- App colors -->
    <color name="tv_color">#3E3E3E</color>
    <color name="color_pager_selector">#0CF2B4</color>
    <color name="color_pager_default">#212121</color>
</resources>

5- According to Demo, we have three views to represent. To display these views, we can use fragment and Recyclerview adapter. For now, we’re going to use Fragments. To achieve this, we will use FragmentStateAdapter class to add these fragments in the ViewPager2.

6- Create a new AdapterViewPager.Java class and add the below lines of code

package com.example.viewpager2example.adapters;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.example.viewpager2example.fragments.FirstFragment;
import com.example.viewpager2example.fragments.SecondFragment;
import com.example.viewpager2example.fragments.ThirdFragment;

public class AdapterViewPager extends FragmentStateAdapter {
    public AdapterViewPager(FragmentActivity fa) {
        super(fa);
    }

    @Override
    public Fragment createFragment(int position) {
        switch (position) {
            case 0:
                return new FirstFragment();
            case 1:
                return new SecondFragment();
            default:
                return new ThirdFragment();

        }
    }

    @Override
    public int getItemCount() {
        return 3;
    }
}

7- As per the demo, We need to create three different layouts to represent views.

8-> Go to res->layout and create a layout file named fragment_first.xml and add the below code

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:background="@color/white"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imgBg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/bg"
            app:layout_constraintBottom_toBottomOf="@+id/imgGirl"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/imgGirl" />

        <ImageView
            android:id="@+id/imgGirl"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/img_girl"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/tvTitle"
            app:layout_constraintTop_toTopOf="parent" />


        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/raleway_extrabold"
            android:text="@string/str_demo_tv"
            android:textColor="@color/tv_color"
            android:textSize="22sp"
            app:layout_constraintBottom_toTopOf="@+id/tvTitle2"
            app:layout_constraintStart_toStartOf="@+id/leftGuideline" />
        <TextView
            android:id="@+id/tvTitle2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/raleway_extrabold"
            android:text="@string/str_demo_tv_1"
            android:textColor="@color/tv_color"
            android:textSize="22sp"
            app:layout_constraintBottom_toTopOf="@+id/tvTagLine"
            app:layout_constraintStart_toStartOf="@+id/leftGuideline" />

        <TextView
            android:id="@+id/tvTagLine"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/lato_light"
            android:text="@string/str_demo_tv_2"
            android:textColor="@color/black"
            android:textSize="12sp"
            app:layout_constraintBottom_toTopOf="@+id/bottomGuideline"
            app:layout_constraintStart_toStartOf="@+id/leftGuideline" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/bottomGuideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_end="100dp" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/leftGuideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_begin="40dp" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

9- Create the FirstFragment.java class and add the below code.

package com.example.viewpager2example.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.example.viewpager2example.R;
import com.example.viewpager2example.databinding.FragmentFirstBinding;

public class FirstFragment extends Fragment {
    private FragmentFirstBinding binding;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_first, container, false);
        return binding.getRoot();
    }
}

10- Go to res->layout and add another layout file called fragment_second.xml and add the below code

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:background="@color/white"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/raleway_extrabold"
            android:text="@string/str_demo_tv_3"
            android:textColor="@color/tv_color"
            android:textSize="22sp"
            app:layout_constraintStart_toStartOf="@+id/leftGuideline"
            app:layout_constraintTop_toTopOf="@+id/topGuideline" />

        <TextView
            android:id="@+id/tvTitle1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/raleway_extrabold"
            android:text="@string/str_demo_tv_4"
            android:textColor="@color/tv_color"
            android:textSize="22sp"
            app:layout_constraintStart_toStartOf="@+id/leftGuideline"
            app:layout_constraintTop_toBottomOf="@+id/tvTitle" />

        <TextView
            android:id="@+id/tvTitle2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/lato_light"
            android:text="@string/str_demo_tv_2"
            android:textColor="@color/black"
            android:textSize="14sp"
            app:layout_constraintStart_toStartOf="@+id/leftGuideline"
            app:layout_constraintTop_toBottomOf="@+id/tvTitle1" />

        <ImageView
            android:id="@+id/imgBg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/bg"
            app:layout_constraintBottom_toBottomOf="@+id/imgMen"
            app:layout_constraintEnd_toEndOf="@+id/imgMen"
            app:layout_constraintStart_toStartOf="@+id/imgMen"
            app:layout_constraintTop_toTopOf="@+id/imgMen" />

        <ImageView
            android:id="@+id/imgMen"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/img_men"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tvTitle2" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/topGuideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_begin="50dp" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/leftGuideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_begin="40dp" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

11- Create the SecondFragment.java file and add the below code.

package com.example.viewpager2example.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.example.viewpager2example.R;
import com.example.viewpager2example.databinding.FragmentSecondBinding;

public class SecondFragment extends Fragment {
    private FragmentSecondBinding binding;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_second,container,false);
        return binding.getRoot();
    }
}

12- For the third view, Go to res->layout and add a new layout resource file called fragment_third.xml and copy&paste the below code.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:background="@color/white"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imgBg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/bg"
            app:layout_constraintBottom_toBottomOf="@+id/imgGirl"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/imgGirl" />

        <ImageView
            android:id="@+id/imgGirl"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/sitting_girl"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/tvTitle"
            app:layout_constraintTop_toTopOf="parent" />


        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/raleway_extrabold"
            android:text="@string/str_demo_tv_5"
            android:textColor="@color/tv_color"
            android:textSize="22sp"
            app:layout_constraintBottom_toTopOf="@+id/tvTitle2"
            app:layout_constraintStart_toStartOf="@+id/leftGuideline" />
        <TextView
            android:id="@+id/tvTitle2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/raleway_extrabold"
            android:text="@string/str_demo_tv_6"
            android:textColor="@color/tv_color"
            android:textSize="22sp"
            app:layout_constraintBottom_toTopOf="@+id/tvTagLine"
            app:layout_constraintStart_toStartOf="@+id/leftGuideline" />

        <TextView
            android:id="@+id/tvTagLine"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/lato_light"
            android:text="@string/str_demo_tv_2"
            android:textColor="@color/black"
            android:textSize="12sp"
            app:layout_constraintBottom_toTopOf="@+id/bottomGuideline"
            app:layout_constraintStart_toStartOf="@+id/leftGuideline" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/bottomGuideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_end="100dp" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/leftGuideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_begin="40dp" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

13- Create a ThirdFragment.java file and add the below code

package com.example.viewpager2example.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.example.viewpager2example.R;
import com.example.viewpager2example.databinding.FragmentThirdBinding;

public class ThirdFragment extends Fragment {
    private FragmentThirdBinding binding;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_third, container, false);
        return binding.getRoot();
    }
}

14- Now we will add a ViewPager2 and TabLayout component in activie_main.xml file. Go to res->layout and open the activie_main.xml file and add the below code

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        tools:context=".MainActivity">

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/btnSkip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/raleway_extrabold"
            android:text="@string/tv_skip"
            android:onClick="onClickSkipBtn"
            android:background="@android:color/transparent"
            android:textSize="16sp"
            android:textColor="@color/tv_color"
            app:layout_constraintEnd_toEndOf="@id/rightGuideline"
            app:layout_constraintTop_toTopOf="@+id/topGuideline" />

        <androidx.viewpager2.widget.ViewPager2
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintBottom_toTopOf="@+id/tabLayoutIndicator"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabLayoutIndicator"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="@color/white"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:tabBackground="@drawable/tab_pager_selector"
            app:tabGravity="center"
            app:tabIndicatorHeight="0dp"
            app:tabPaddingEnd="15dp"
            app:tabPaddingStart="15dp" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/topGuideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_begin="20dp" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/rightGuideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_end="20dp" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

15- Open the MainActivity.java file. Comments added to understand the each line of code. If you have any confusion, you can ask via comments. Add the below code in MainActivity.java file

package com.example.viewpager2example;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.example.viewpager2example.adapters.AdapterViewPager;
import com.example.viewpager2example.databinding.ActivityMainBinding;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        initComponents();;
    }

    /**
     * initiate the ViewPagerAdapter
     * set the adapter to view pager
     * if you want to display the circular dot, then you need to add TabLayoutMediator
     * Create the Object of TabLayoutMediator class and then call the attach method
     */
    private void initComponents(){
        AdapterViewPager adapterViewPager = new AdapterViewPager(this);
        binding.viewPager.setAdapter(adapterViewPager);
        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(binding.tabLayoutIndicator, binding.viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                // TODO: 8/7/21 do whatever you want to do according to your logic or requirements
            }
        });
        tabLayoutMediator.attach();
    }

    /**
     * On skip button, open another activity or view according to your project requirements
     * @param v button view
     */
    public void onClickSkipBtn(View v){
        Toast.makeText(this,"Skip Button Clicked",Toast.LENGTH_LONG).show();
    }
}

16- All the resouces that being used in this demo, you can take from the source code.

Download the soruce code

Thanks for reading the tutorial. Subscribe to my YouTube channel. Like and Share my Facebook page with your friends.

Write A Comment