avatarErselan Khan

Summary

This context provides a comprehensive guide on how to dynamically update fragments within ViewPager2 in Android applications, emphasizing the benefits of using ViewPager2 over its predecessor.

Abstract

The provided content is an Android tutorial focused on the implementation and dynamic manipulation of fragments within ViewPager2. It begins by explaining the concept of ViewPager, its use cases, and the advantages of the newer ViewPager2 library, such as active development support, vertical paging, right-to-left (RTL) paging, and integration with RecyclerView features like DiffUtil. The tutorial then guides developers through setting up ViewPager2 in a project, including adding dependencies, creating the necessary XML layout, and writing the corresponding MainActivity code. It demonstrates how to create an adapter to manage fragments and how to refresh, add, or remove fragments at runtime, using methods like notifyItemChanged(index) and notifyDatasetChanged(). The article concludes with an invitation for readers to engage with the author by sharing the article, supporting the author through a 'Buy me a pizza' link, or reaching out for further questions.

Opinions

  • The author advocates for the adoption of ViewPager2 over the original ViewPager due to its active development and enhanced features.
  • The tutorial suggests that ViewPager2's integration with RecyclerView makes it a more robust and flexible choice for developers.
  • The author expresses enthusiasm for the ease with which developers can update fragments within ViewPager2, highlighting this as a key benefit.
  • By providing a GitHub repository with the source code for the demo, the author encourages hands-on learning and experimentation with ViewPager2.
  • The author values community engagement and support, as indicated by the invitation to share the article, contribute financially to the author's work, or contact the author for further assistance.

Dynamically Update/Refresh/Reload ViewPager2 Fragments

In this Android tutorial, I will show you how we can update/refresh/reload the fragments inside Viewpager2 dynamically. But before deep into it, I would like to clarify the concept of Viewpager and when and why we should use it.

Want to check spelling mistakes on your documents? download Spelling Checker from the Play Store.

What is ViewPager and what are the perfect cases to use it?

The ViewPager is the widget that allows the user to swipe left or right to see an entirely new screen. In a sense, it’s just a nicer way to show the user multiple tabs. It also has the ability to dynamically add and remove pages (or tabs) at any time. The Android team recently introduced the advanced version of ViewPager, which is ViewPager2. Here are some reasons why we should move to the ViewPager2 library:

  1. The primary reason to migrate is that ViewPager2 is receiving active development support and ViewPager is not.
  2. ViewPager2 supports vertical paging in addition to traditional horizontal paging. You can enable vertical paging for a ViewPager2 element by setting its android:orientation
  3. ViewPager2 supports right-to-left (RTL) paging. RTL paging is enabled automatically were appropriate based on locale, but you can also manually enable RTL paging for a ViewPager2 element by setting its android:layoutDirection
  4. ViewPager2 supports paging through a modifiable collection of fragments, calling de>notifyDatasetChanged() to update the UI when the underlying collection changes.
  5. ViewPager2 is built on RecyclerView, which means it has access to the DiffUtil utility class. This results in several benefits, but most notably it means that ViewPager2 objects natively take advantage of the dataset change animations from the RecyclerView class.

Now It’s time to implement the ViewPager2 library inside our project. First, we need to add the dependencies for ViewPager2:

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

Create an Activity class and XML for our activity, we call it as MainActivty and activity_main respectively. Open your XML file and put the code inside your XML file:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".ui.MainActivity">

    <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:title="ViewPager2"
        app:titleTextColor="@color/white"
        android:background="@color/black"
        android:id="@+id/toolbar"/>

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Now Open your MainActivity class and add the below code inside your activity:

class MainActivity : AppCompatActivity() {

    private lateinit var viewPager: ViewPager2
    private lateinit var viewPagerAdapter: ViewPagerAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        viewPager = findViewById(R.id.pager)
        val fragments =
            mutableListOf(
                FirstFragment(),
                SecondFragment(),
                ThirdFragment()
            )

        viewPager.offscreenPageLimit = 3
        viewPagerAdapter = ViewPagerAdapter(supportFragmentManager, fragments, lifecycle)
        viewPager.adapter = viewPagerAdapter

        refreshSecondFragmentText()
    }

    private fun refreshSecondFragmentText() {
        Handler(Looper.getMainLooper()).postDelayed({
            viewPagerAdapter.refreshFragment(1, ForthFragment())
        }, 5000)
    }
}

As you can see we are updating our 2nd position item of ViewPager2 after 5 seconds and replacing the SecondFragment with our ForthFragment by calling the method refreshSecondFragmentText().

Now it’s time to see our custom ViewPagerAdapter class:

class ViewPagerAdapter(
    fragmentManager: FragmentManager, var fragments: MutableList<Fragment>, lifecycle: Lifecycle
    ) : FragmentStateAdapter(fragmentManager, lifecycle) {
    override fun getItemCount(): Int {
        return fragments.size
    }
    override fun createFragment(position: Int): Fragment {
        return fragments[position]
    }

    fun add(index: Int, fragment: Fragment) {
        fragments.add(index, fragment)
        notifyItemChanged(index)
    }

    fun refreshFragment(index: Int, fragment: Fragment) {
        fragments[index] = fragment
        notifyItemChanged(index)
    }

    fun remove(index: Int) {
        fragments.removeAt(index)
        notifyItemChanged(index)
    }

    override fun getItemId(position: Int): Long {
        return fragments[position].hashCode().toLong()
    }

    override fun containsItem(itemId: Long): Boolean {
        return fragments.find { it.hashCode().toLong() == itemId } != null
    }
}

We can easily add, remove and refresh our fragments at any time by using the above ViewPagerAdapter. As we already know that ViewPager2 is built on RecyclerView that’s why it’s easy to update only one item by calling the method notifyItemChanged(index). If we want to update all items then we can also do this by simply calling the notifyDatasetChanged() method.

That’s it for now. I will cover more topics on Android in my upcoming articles.

Show your love by sharing this article with your fellow developers or Buy me a pizza by clicking this link https://www.buymeacoffee.com/erselankhan.

(Again, the source for this demo is https://github.com/arsalankhan994/viewpager2. Follow me for more content about Android and other technologies. If you have any questions, go ahead and ask me here or email me at [email protected] and I’ll do my best to respond.)

Android
Android App Development
Viewpager
Github
Viewpager2
Recommended from ReadMedium