Viewpager in android

Hi folks,
In this article, we’ll learn about ViewPager to create swipe views for switching between different screens or fragments in Android apps.

Viewpager is a very good feature of android development, it facilitates users to traverse from one view to another view by swiping the screen horizontally.

Android ViewPager

Android ViewPager widget is introduced by the Design support library and it allows us to swipe left or right through “pages” of content on an entirely new screen which are usually different fragments. ViewPager is a kind of layout manager that allows the user to flip left and right through pages of data. ViewPager objects can animate screen slides automatically. ViewPager class works with PagerAdapter which provides pages.

PagerAdapter

PagerAdapter is the base class providing the adapter to populate pages inside of a ViewPager. ViewPager uses PagerAdapter objects as a supply for new pages to display, so the PagerAdapter will use the fragment classes.

PagerAdapter will properly determine that how many pages exist and which fragment to display for each page of the adapter by creating a more specific implementation of PagerAdapter, such as FragmentPagerAdapter or FragmentStatePagerAdapter.

Note: For sliding screens/views, we recommend the improved ViewPager2 library.

Example

In this example we’ll implement viewpager that swipes through three different fragments.

1. Create a New Project –

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from templates to implement ViewPager in android app .

2. Implement Dependency –

After creating a new project, specify the following dependency in your build.gradle.

dependencies {
   //Material Design Support library
    implementation 'com.google.android.material:material:1.1.0'
}

Try to add the latest version of the Material Design library or Dependency. Once that’s done, save the file and perform a Gradle sync.

3. Add ViewPager to Layout –

Add the ViewPager to your layout file of your MainActivity

<androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

Open res -> layout -> activity_main.xml  file and just implement the following xml code .

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

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

4. Implement PagerAdapter  

Now we’ll create PagerAdapter by defining a class that extends the FragmentStatePagerAdapter class.

ViewPagerAdapter.java

package net.technxt.androidviewpager.Adapter;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;

import java.util.ArrayList;

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

    private ArrayList<Fragment> mFragmentList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment) {
        mFragmentList.add(fragment);
    }

}

5. Create the Fragments for the ViewPager 

Now we need to define three different fragments for each screen in the ViewPager. Each screen contains one Fragment in the Viewpager.

FragmentOne

Each Fragment contains just one TextView.

package net.technxt.androidviewpager.Fragment;

import android.os.Bundle;

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

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import net.technxt.androidviewpager.R;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class FragmentOne extends Fragment {

    TextView txt;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_one, container, false);
        txt = view.findViewById(R.id.txt);
        txt.setText("Fragment One");
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }
}

FragmentTwo

package net.technxt.androidviewpager.Fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import net.technxt.androidviewpager.R;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class FragmentTwo extends Fragment {

    TextView txt;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_two, container, false);
        txt = view.findViewById(R.id.txt);
        txt.setText("Fragment Two");
        return view;
    }
}

FragmentThree

package net.technxt.androidviewpager.Fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import net.technxt.androidviewpager.R;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class FragmentThree extends Fragment {

    TextView txt;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_three, container, false);
        txt = view.findViewById(R.id.txt);
        txt.setText("Fragment Three");
        return view;
    }
}

6. Setup ViewPager to the MainActivity 

Finally, let’s implement the ViewPager and setup the viewpager adapter.

package net.technxt.androidviewpager.Activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;

import net.technxt.androidviewpager.Adapter.ViewPagerAdapter;
import net.technxt.androidviewpager.Fragment.FragmentOne;
import net.technxt.androidviewpager.Fragment.FragmentThree;
import net.technxt.androidviewpager.Fragment.FragmentTwo;
import net.technxt.androidviewpager.R;

public class MainActivity extends AppCompatActivity {

    ViewPager viewPager;
    ViewPagerAdapter viewPagerAdapter;

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

        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragment(new FragmentOne());
        viewPagerAdapter.addFragment(new FragmentTwo());
        viewPagerAdapter.addFragment(new FragmentThree());

        viewPager.setAdapter(viewPagerAdapter);
    }

}

Finally run your application.

7.Output –

The output of our Android ViewPager example application is shown below:

Android ViewPager Example
Android ViewPager Example

You can download the project Android Viewpager from the below link.

Thanks for reading! If you enjoyed this article, please click the 👍 Like button and share it to help others find it! Feel free to leave a comment 💬 below.
Have feedback? Let’s connect on Facebook.

%d bloggers like this: