TabLayout with ViewPager2 Tutorial in Android

ViewPager2 is an enhancement of ViewPager view in Android.

Advantage of ViewPager2:

i) ViewPager2 supports vertical paging that means you can scroll pages in vertical directions.

ii) For enabling vertical paging you need use orientation like below:

android:orientation="vertical"

iii) You can also enable vertical paging through the java code like below:

viewPager.setOrientation(ViewPager2.ORIENTATION_VERTICAL);

iv) ViewPager2 supports RTL (Right To Left) paging.

v) Basically RTL paging is enabled automatically based on locale, but you can also enable RTL paging manually like below:

android:layoutDirection="rtl"

vi) You can also enable direction through java code like below:

viewPager.setLayoutDirection(LAYOUT_DIRECTION_RTL);

vii) ViewPager2 supports paging through a modified collection of fragments, calling notifyDatasetChanged() to update the UI when your collection fragment is changed.


Now lets see example of ViewPager2 in Android:


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:title="TabLayout with ViewPager2"
            app:titleTextColor="@color/white" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabbed"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </com.google.android.material.appbar.AppBarLayout>


    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        aandroid:orientation="vertical" />

</LinearLayout>

extra.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Extra"
        android:textSize="30sp" />

</RelativeLayout>

register.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Register"
        android:textSize="30sp" />

</RelativeLayout>

login.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Login"
        android:textSize="30sp" />

</RelativeLayout>

MainActivity.java

package com.example.firstapp;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import org.jetbrains.annotations.NotNull;

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

import static androidx.core.view.ViewCompat.LAYOUT_DIRECTION_RTL;

public class MainActivity extends AppCompatActivity {

    //Create a fragments Collection
    List<Fragment> fragments = new ArrayList();
    //Create a Titles Collection
    List<String> titles = new ArrayList();

    @SuppressLint("WrongConstant")
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onCreate(@Nullable 
    @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //add fragments into a fragment collection
        fragments.add(new LoginFragment());
        fragments.add(new RegisterFragment());
        fragments.add(new ExtraPage());
        //add titles into a title collection
        titles.add("Login");
        titles.add("Register");
        titles.add("Extra");


        TabLayout tabLayout = findViewById(R.id.tabbed);
        ViewPager2 viewPager = findViewById(R.id.viewpager);
        
        //viewPager.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
        //viewPager.setLayoutDirection(LAYOUT_DIRECTION_RTL);
        
        viewPager.setAdapter(new MyWhatsAppTab(this));
        
        //TabLayoutMediator is a callback interface that must be implemented
        // to set the text and styling of newly create tabs.
        
        new TabLayoutMediator(tabLayout, viewPager,
                (tab, position) -> tab.setText(titles.get(position))
                //TabLayout and the ViewPager2 together.
                // Must be called after ViewPager2 has an adapter set.
        ).attach();

    }

    class MyWhatsAppTab extends FragmentStateAdapter {

        public MyWhatsAppTab(@NonNull @NotNull 
        FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @NotNull
        @Override
        public Fragment createFragment(int position) {
            return fragments.get(position);
        }

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

}
  

RegisterFragment.java

package com.example.firstapp;

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.fragment.app.Fragment;

import org.jetbrains.annotations.NotNull;

public class RegisterFragment extends Fragment {

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater,
                     @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, 
                     @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.register, container, false);
    }
}
  

ExtraFragment.java

package com.example.firstapp;

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.fragment.app.Fragment;

import org.jetbrains.annotations.NotNull;

public class ExtraFragment extends Fragment {

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater,
                     @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, 
                     @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.extra, container, false);
    }
}
  

LoginFragment.java

package com.example.firstapp;

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.fragment.app.Fragment;

import org.jetbrains.annotations.NotNull;

public class LoginFragment extends Fragment {

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater,
                     @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, 
                     @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.login, container, false);
    }
}