ViewPager Using Fragments in Android with Example


The Android ViewPager widget is a vital component in building swipeable or scrollable user interfaces. It allows the user to flip left and right through pages of data, which is a common pattern seen in various applications today. In this comprehensive guide, we will explore how to use ViewPager with Fragments in Android, fortified with a practical example to facilitate your understanding.

Introduction to ViewPager and Fragments

Before we dive into the coding, let's understand the basics of ViewPager and Fragments −

  • ViewPager − A layout manager that allows the user to flip left and right through pages of data. It's an ideal tool when you have a sequence of pages to show to the user.

  • Fragments − A Fragment represents a portion of the user interface or an aspect of app behavior, encapsulated into modular and reusable classes. Multiple fragments can exist within an activity, and they contribute towards creating a flexible and responsive user interface.

Combining ViewPager with Fragments allows us to create a swipeable views feature, which is common in many popular Android applications.

Setting up ViewPager with Fragments: A Step-by-Step Guide

Let's create an Android application to demonstrate the use of ViewPager with Fragments.

Step 1− Setting Up The Project

Create a new Android Studio project. In the project wizard, choose an Empty Activity and set the language to Java

Step 2 − Adding Dependencies

Add the ViewPager2 dependency to your build.gradle (Module) file −

dependencies {
   implementation    'androidx.viewpager2:viewpager2:1.1.0-alpha01'
}

Don't forget to sync the project after adding the dependency

Step 3 −

Create three new Fragments - FirstFragment, SecondFragment, and ThirdFragment. Each Fragment will represent a page in our ViewPager

Here's an example of how you can create FirstFragment:

public class FirstFragment extends Fragment {
   @Nullable
   @Override
   public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
      return inflater.inflate(R.layout.fragment_first, container, false);
   }
}

Step 4 − Creating the Adapter

Next, create a FragmentStateAdapter that will manage the fragments and provide them to the ViewPager as needed.

public class ViewPagerAdapter extends FragmentStateAdapter {
   public ViewPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
      super(fragmentActivity);
   }
   @NonNull
   @Override
   public Fragment createFragment(int position) {
      switch (position) {
      case 0:
         return new FirstFragment();
      case 1:
         return new SecondFragment();
      case 2:
         return new ThirdFragment();
         }
      return new FirstFragment();
   }
   @Override
   public int getItemCount() {
      return 3;
   }
}

Step 5 − Setting Up ViewPager in Activity

Finally, in your MainActivity, initialize the ViewPager and set its adapter

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      ViewPager2 viewPager = findViewById(R.id.viewPager);
      viewPager.setAdapter(new ViewPagerAdapter(this));
   }
}

Make sure you have a ViewPager2 in your activity_main.xml layout file −

   <androidx.viewpager2.widget.ViewPager2
   android:id="@+id/viewPager"
   android:layout_width="match_parent"
   android:layout_height="match
   android:layout_height="match_parent" />

After implementing these steps, each swipe will move to a different fragment, presenting the user with a new screen

Enhancing the ViewPager Experience

While the basic implementation is complete, there are a few additional features you can add to enhance the user's experience.

Adding Page Titles

For instance, you can add page titles to each fragment in your ViewPager. This can be achieved by overriding the getPageTitle() method in your ViewPagerAdapter class −

@Override
public CharSequence getPageTitle(int position) {
   switch (position) {
      case 0:
         return "First";
      case 1: 
         return "Second";
      case 2:
         return "Third";
      }
   return null;
}   

Incorporating TabLayout with ViewPager

A common use case is to combine ViewPager with a TabLayout, providing a more interactive and intuitive swipe experience. Once you have a TabLayout set up in your XML file, you can link it with the ViewPager in your MainActivity −

TabLayout tabLayout = findViewById(R.id.tab_layout);
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(
   tabLayout, viewPager, true, new TabLayoutMediator.TabConfigurationStrategy() {
      @Override
      public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
        tab.setText("Tab " + (position + 1));
      }
   });
tabLayoutMediator.attach();

Don't forget to add the TabLayout dependency to your build.gradle file:

implementation 'com.google.android.material:material:1.3.0'

Conclusion

The ViewPager widget in Android, combined with Fragments, creates an efficient way to create swipeable views in your application. This feature gives a seamless browsing experience and is a crucial part of modern Android development

Updated on: 19-Jul-2023

560 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements