FragmentPagerAdapter deprecated

2020-05-24 19:23发布

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]
        }
    }

2条回答
劳资没心,怎么记你
2楼-- · 2020-05-24 20:05

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)

查看更多
老娘就宠你
3楼-- · 2020-05-24 20:10

The javadocs actually has the following deprecation notice on FragmentPagerAdapter:


This class is deprecated.

Switch to ViewPager2 and use FragmentStateAdapter instead.


查看更多
登录 后发表回答