Twitter LogoFacebook Logo
ViewPager
Hello, in this tutorial, I will be talking about the ViewPager for Android.
By: King

The ViewPager is a view that we can add to our layout so we can swipe vertically or horizontally across the screen to flip through multiple pages.

There are 4 components that you will need.

1) A fragment to represent each page in the ViewPager
2) The ViewPager
3) Adapter to filter and control the behavior of the ViewPager
4) An array of data.

Before we begin, add the dependency for the ViewPager. Go to the app level build gradle file and add the implementation.

App Grade File

dependencies {
    implementation "androidx.viewpager2:viewpager2:1.0.0"
}

For the latest version, visit the android developer website. 

https://developer.android.com/jetpack/androidx/releases/viewpager2#androidx-deps

Creating the Fragment for Each Page

To begin, create a fragment that will represent the pages for the view pager.

Remember to have the Android mode selected and then right click on the project folder. Go to New > Fragment > and select the Blank fragment.

Image from Codeible.com

Rename the fragment and click finish. 

Image from Codeible.com

Go into the fragment's xml layout file. Swap to the code view and change the frame layout into a constraint layout.

<?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"
    ...>

</androidx.constraintlayout.widget.ConstraintLayout>

Replace the TextView with a button and add the constraints so it will be in the center of the screen. 

<?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"
    ...>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Now, go to the Fragment’s class file and remove all the unnecessary code except the constructor and the onCreateView() method.

public class MyFragment extends Fragment {

    public MyFragment () {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_my, container, false);
    }
}

Then create a reference for the button in the onCreateView() method. 

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_my, container, false);
    Button button = root.findViewById(R.id.button);
    return root;
}

Define a String variable call title and add a parameter to the constructor to accept a string. Then set the value of the title variable to the string that is coming in.

String title;
public MyFragment (String title) {

   this.title = title;

}

Lastly, call the setText() method from the button object and pass in the title.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

    View root = inflater.inflate(R.layout.fragment_my, container, false);

    Button button = root.findViewById(R.id.button);
    button.setText(this.title);

    return root;
}

Now, we have our page.

Creating the ViewPager

The next step is to add the ViewPager. Go to the xml layout file that you want to add the view pager to. 

In the palette, search for ViewPager and add the pager to the layout. 

Image from Codeible.com

Then in the Attribute pane, give it an id.

Image from Codeible.com

Go to the fragment or activity that is using the layout with the ViewPager and declare a reference for it.

public class MainActivity extends AppCompatActivity {

    ViewPager2 viewPager;

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

        viewPager = findViewById(R.id.pager1);

    }

}

Creating and Attaching the Adapter

To create the Adapter, define a class and have it extend FragmentStateAdapter

private class ScreenSlidePagerAdapter extends FragmentStateAdapter {

}

Then hover and click on the class definition. You will see a red lightbulb icon. Click on it and select the “Implement methods” option.

Image from Codeible.com

Repeat the same step and select the “Create constructor matching super” option.

Image from Codeible.com

You will see a few choices that you can make. Depending on where you are going to declare and initialize the adapter, you should choose what is best for you. If you do not know, select all the options by pressing shift and clicking on the last item and then click OK.

private class ScreenSlidePagerAdapter extends FragmentStateAdapter {

        public ScreenSlidePagerAdapter( FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        public ScreenSlidePagerAdapter(Fragment fragment) {
            super(fragment);
        }

        public ScreenSlidePagerAdapter(FragmentManager fragmentManager,  Lifecycle lifecycle) {
            super(fragmentManager, lifecycle);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return null;
        }

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

In the createFragment() method, return the fragment that we created earlier for the pages.

@NonNull
@Override
public Fragment createFragment(int position) {
    return new MyFragment("Hello World");
}

And in the getItemCount() method, return 10. This will tell our ViewPager that we have 10 pages.

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

Lastly, add the adapter to the ViewPager by calling setAdapter() and pass in the adapter object.

public class MainActivity extends AppCompatActivity {

    ViewPager2 viewPager;

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

        viewPager = findViewById(R.id.pager1);
        viewPager.setAdapter(new ScreenSlidePagerAdapter());

    }

}

If we run the app, we will see that we can flip through our pages by swiping left or right.

Image from Codeible.com

Display Different Data

If you notice, all our pages are displaying the same text. To change this, we need to create some data and modify the adapter.

Declare a String array and then populate it with some data.

private class ScreenSlidePagerAdapter extends FragmentStateAdapter {
      
    String [] data = {"Apple", "Banana", "Cherry", "Durian"}
        ...
}

In the getItemCount() method of the adapter, replace 10 with the length of the array.

@Override
public int getItemCount() {
      return data.length;
}

In the createFragment() method, instead of using a hard coded value when instantiating the fragment, pass in the data.

@NonNull
@Override
public Fragment createFragment(int position) {
    return new MyFragment( data[position] );
}

If we run the app again, each page will display a different text.

Image from Codeible.com

Sign In