Search code examples
androidandroid-recyclerviewlifecyclepage-lifecycleandroid-viewpager2

How do I implement a method to get and return the LifeCycle


I have issue with the FragmentStateAdapter asking for LifeCycle, kindly help how I can set and pass the LifeCycle in the line of code below.

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

Here is the myViewPagerAdapter method

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

    }
}

After some digging, I got this, LifeCycle is @NonNull

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

Help me complete this method to return the current LifeCycle

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

Solution

  • Just call getLifecycle() which returns a LifeCycle object.

    See more : https://developer.android.com/reference/android/arch/lifecycle/LifecycleOwner.html#getLifecycle()