ViewPager2适配器-FragmentActivity/Fragment/FragmentManager之间的区别 [英] ViewPager2 adapters - difference between FragmentActivity / Fragment / FragmentManager

查看:485
本文介绍了ViewPager2适配器-FragmentActivity/Fragment/FragmentManager之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此 ViewPager2视频中注意到,有3种不同的方式来声明Fragment的适配器.它们之间有什么区别?使用ViewPager2的带有选项卡的滑动视图应使用哪个1?

I noticed in this ViewPager2 video that there are 3 different ways of declaring an adapter with Fragments. What's the difference between them and which 1 should be used for swipe views with tabs using ViewPager2?

选项1(推荐)

class MyFragmentAdapter (
    fa: FragmentActivity
) : FragmentStateAdapter(fa)

选项2

class MyFragmentAdapter (
    f: Fragment
) : FragmentStateAdapter(f)

选项3

class MyFragmentAdapter (
    fm: FragmentManager,
    l: Lifecycle
) : FragmentStateAdapter(fm, l)

推荐答案

使用Viewpager2,只有一种适配器类型 FragmentStateAdapter

With Viewpager2 there is only one adapter type FragmentStateAdapter

它们的行为似乎没有什么区别,它们只是同一FragmentStateAdapter的不同构造函数.使用哪一个似乎主要取决于您在哪里创建viewpager2

There does not seem to be a difference in how they behave, they are just different constructors of the same FragmentStateAdapter. Which one to use seems to mostly depend on where you are creating the viewpager2

如果您要在Activity中创建viewpager2,请给它一个FragmentActivity,这是第三个方法的快捷方式

Give it a FragmentActivity if you are creating the viewpager2 in an Activity, this is a shortcut to the third method

Give是Fragment,这是第三个方法的快捷方式

Give is a Fragment if you are creating the viewpager2 in a parent Fragement, this is a shortcut to the third method

FragmentManagerLifecycle的第三个实际上是工作所需的内容,请参见viewpager2构造函数的源代码

The third of FragmentManager and Lifecycle is actually what it requires to work, see the source code for viewpager2 constructors https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/viewpager2/viewpager2/src/main/java/androidx/viewpager2/adapter/FragmentStateAdapter.java#109

这篇关于ViewPager2适配器-FragmentActivity/Fragment/FragmentManager之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆