Android & Kotlin

ViewPager2 with Fragments Android Example

Pinterest LinkedIn Tumblr

In this post, I’ll learn viewpager2 with fragments implementation in Android. ViewPager2 is an optimized version of ViewPager. In the previous article, I was explained the implementation of ViewPager2 with TabLayout Android.

Internally ViewPager2 uses RecyclerView component to display swipeable content. ViewPager2 have so many new features, In this android example post, we’ll learn ViewPager2 implementation with Fragments.

Steps of Implementation ViewPager2 with Fragments
  • Create a project with androidx
  • Add the ViewPager2 dependencies
  • Update some resource file, that needed for this demo
  • Create fragments for ViewPager2
  • Create a subclass of FragmentStateAdapter
  • Add the ViewPager in activity layout
  • Finally set the FragmentStateAdapter on ViewPager
1. Create a project with Androidx

Let’s open the Android Studio to create a project with AndroidX.

2. Add the ViewPager2 dependencies

Open the app-level build. gradle file and add below dependencies

  implementation 'androidx.viewpager2:viewpager2:1.0.0-beta04'
  implementation 'androidx.fragment:fragment-ktx:1.2.0-alpha04'
  implementation 'com.google.android.material:material:1.1.0-alpha10'
3. Update some resource file

Add few color items in color.xml files

  <?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="colorPrimary">#008577</color>
  <color name="colorPrimaryDark">#00574B</color>
  <color name="colorAccent">#D81B60</color>

  <color name="red_100">#F44336</color>
  <color name="red_300">#3F51B5</color>
  <color name="red_500">#9C27B0</color>
  <color name="red_700">#2196F3</color>
  <color name="blue_100">#00BCD4</color>
  <color name="blue_300">#7BAAF7</color>
  <color name="blue_500">#009688</color>
  <color name="blue_700">#3367D6</color>
  <color name="green_100">#CDDC39</color>
  <color name="green_300">#57BB8A</color>
  <color name="green_500">#673AB7</color>
  <color name="green_700">#0B8043</color>

</resources>
4. Create fragments for ViewPager2

Simply creates a fragment named is CardFragment with XML layout. Open the layout file paste below code.

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

  <TextView
      android:id="@+id/tv_counter"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:gravity="center"
      android:textColor="#fff"
      android:textSize="20sp"
      android:textStyle="bold"
      tools:text="@string/hello_blank_fragment"
      />

</FrameLayout>
Bind above fragment layout with file

Let’s paste below code in the CardFragment.java file. In this fragment have a TextView

package com.viewpager2example;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CardFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CardFragment extends Fragment {

  private static final String ARG_COUNT = "param1";
  private Integer counter;

  private int[] COLOR_MAP = {
      R.color.red_100, R.color.red_300, R.color.red_500, R.color.red_700, R.color.blue_100,
      R.color.blue_300, R.color.blue_500, R.color.blue_700, R.color.green_100, R.color.green_300,
      R.color.green_500, R.color.green_700
  };

  public CardFragment() {
    // Required empty public constructor
  }

  public static CardFragment newInstance(Integer counter) {
    CardFragment fragment = new CardFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_COUNT, counter);
    fragment.setArguments(args);
    return fragment;
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
      counter = getArguments().getInt(ARG_COUNT);
    }
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_card, container, false);
  }

  @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    view.setBackgroundColor(ContextCompat.getColor(getContext(), COLOR_MAP[counter]));
    TextView textViewCounter = view.findViewById(R.id.tv_counter);
    textViewCounter.setText("Fragment No " + counter);
  }
}
5. Create a subclass of FragmentStateAdapter
package com.viewpager2example;

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

public class ViewPagerAdapter extends FragmentStateAdapter {
  private static final int CARD_ITEM_SIZE = 10;

  public ViewPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
    super(fragmentActivity);
  }

  @NonNull @Override public Fragment createFragment(int position) {
    return CardFragment.newInstance(position);
  }

  @Override public int getItemCount() {
    return CARD_ITEM_SIZE;
  }
}
6. Add the ViewPager in activity 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >

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

</androidx.constraintlayout.widget.ConstraintLayout>
7. Finally set the FragmentStateAdapter on ViewPager
package com.viewpager2example;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.widget.ViewPager2;

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.view_pager);
    viewPager.setAdapter(createCardAdapter());
  }

  private ViewPagerAdapter createCardAdapter() {
    ViewPagerAdapter adapter = new ViewPagerAdapter(this);
    return adapter;
  }
}

Conclusion

In this android app example, we have learned the implementation of ViewPager2 with Fragment in Android. I hope it’s helpful for you.

Keep in touch

If you want to keep in touch and get an email when I write new blog posts, follow me on facebook or subscribe to usIt only takes about 10 seconds to register. 

2 Comments

  1. Hello!

    I did follow your post, and I get this error:

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void androidx.viewpager2.widget.ViewPager2.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)’ on a null object reference

    …because a null object reference in this line:

    viewPager.setAdapter(createCardAdapter());

    • Kees Dil

      Hi,

      did you build onCreate in MainActivity in a right way ?

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.l_mainactivity);
      viewPager = findViewById(R.id.view_pager);
      viewPager.setAdapter(createCardAdapter());
      }

Write A Comment