不推荐使用 FragmentPagerAdapter

FragmentPagerAdapter deprecated(不推荐使用 FragmentPagerAdapter)

本文介绍了不推荐使用 FragmentPagerAdapter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自 API 27 起,FragmentPagerAdapter 已被弃用.最好的替代方法是什么?

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

就我而言,我知道需要使用 super(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) 之类的东西,但我不知道在我的代码中需要去哪里.

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

但是 class MyViewPagerAdapter(manager: FragmentManager) 中的 FragmentPagerAdapter : FragmentPagerAdapter(manager){ 被划掉了.

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

推荐答案

UPDATE 2021-06-14:此时,ViewPager 本身已被弃用.从技术上讲,ViewPager 并没有被弃用,但是两个具体的 PagerAdapter 实现——FragmentPagerAdapterFragmentStatePagerAdapter——被弃用了.理想情况下,切换到其他东西,例如 ViewPager2 或 可组合的寻呼机在伴奏中.

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.

替换:

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

与:

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

(假设 MyViewPagerAdapter 不需要此值即可配置)

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

这篇关于不推荐使用 FragmentPagerAdapter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:不推荐使用 FragmentPagerAdapter

基础教程推荐