Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FragmentPagerAdapter deprecated

Since API 27 FragmentPagerAdapter is deprecated. What's the best alternative to use for this?

In my case, I understand something like super(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) would need to be used, but I don't know where within my code this needs to go.

I got these imports in my class:

import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter 

but FragmentPagerAdapter in class MyViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager){ is crossed out.

class MyViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager){         private val fragmentList : MutableList<androidx.fragment.app.Fragment> = ArrayList()         private val titleList : MutableList<String> = ArrayList()          override fun getItem(position: Int): androidx.fragment.app.Fragment {             return fragmentList[position]         }          override fun getCount(): Int {             return fragmentList.size         }          fun addFragment(fragment: androidx.fragment.app.Fragment, title: String){             fragmentList.add(fragment)             titleList.add(title)         }          override fun getPageTitle(position: Int): CharSequence? {             return titleList[position]         }     } 
like image 507
wbk727 Avatar asked Jun 26 '19 17:06

wbk727


People also ask

Is ViewPager deprecated?

This function is deprecated.

What is FragmentPagerAdapter?

Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page. This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs.

What is difference between ViewPager and ViewPager2?

ViewPager2 is an improved version of the ViewPager library that offers enhanced functionality and addresses common difficulties with using ViewPager . If your app already uses ViewPager , read this page to learn more about migrating to ViewPager2 .


1 Answers

UPDATE 2021-06-14: At this point, ViewPager itself is all but deprecated. Technically, ViewPager is not deprecated, but the two concrete PagerAdapter implementations — FragmentPagerAdapter and FragmentStatePagerAdapter — are deprecated. Ideally, switch to something else, such as ViewPager2 or the pager composable in Accompanist.

Replace:

class MyViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager) 

with:

class MyViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) 

(assuming that MyViewPagerAdapter does not need this value to be configurable)

like image 154
CommonsWare Avatar answered Sep 22 '22 05:09

CommonsWare