3

我对生命周期的FragmentStateAdapter要求有疑问,请帮助我如何在下面的代码行中设置和传递生命周期。

viewPager2.adapter = myViewPagerAdapter(supportFragmentManager, getCurrentLifeCycle())

这是myViewPagerAdapter方法

private fun myViewPagerAdapter(fm: FragmentManager, lifeCycle: Lifecycle): RecyclerView.Adapter<*> {
    //val items = items // avoids resolving the ViewModel multiple times

    return object : FragmentStateAdapter(fm, lifeCycle) {
        override fun getItemCount(): Int {
            // Show fragments.size total pages.
            return fragments.size
        }

        private val fragments = arrayOf(
            MyPostsFragment(),
            RecentPostsFragment()
        )

        override fun createFragment(position: Int): Fragment {
            return fragments[position]
        }

    }
}

经过一番挖掘,我得到了这个,LifeCycle 是@NonNull

public FragmentStateAdapter(@NonNull FragmentManager fragmentManager,
        @NonNull Lifecycle lifecycle) {
    mFragmentManager = fragmentManager;
    mLifecycle = lifecycle;
    super.setHasStableIds(true);
}

帮我完成这个方法返回当前的LifeCycle

private fun getCurrentLifeCycle(): LifeCycle { return ??? }
4

1 回答 1

2

只需调用getLifecycle()which 返回一个LifeCycle对象。

查看更多:https://developer.android.com/reference/android/arch/lifecycle/LifecycleOwner.html#getLifecycle()

于 2019-06-19T07:10:53.787 回答