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:
- The primary reason to migrate is that ViewPager2 is receiving active development support and ViewPager is not.
- ViewPager2 supports vertical paging in addition to traditional horizontal paging. You can enable vertical paging for a ViewPager2 element by setting its
android:orientation - 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 - ViewPager2 supports paging through a modifiable collection of fragments, calling
de>notifyDatasetChanged () to update the UI when the underlying collection changes. - ViewPager2 is built on
RecyclerView, which means it has access to theDiffUtil utility class. This results in several benefits, but most notably it means thatViewPager2objects natively take advantage of the dataset change animations from theRecyclerViewclass.

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.)





