How to know primary fragment item of FragmentStateAdapter

324 views Asked by At

I have a view pager type FragmentStateAdapter and would like to know when the primary fragment is in position e.g. 100% visible. Does FragmentStateAdapter even support this? I've already tried approaches on this post with no luck.

Each fragment in the pager has some control over the host activity, but the control must be mutually exclusive. So like for example depending on which fragment is 100% visible, a button in the host activity layout will change color. But the color must depend on which fragment is primary, not on which fragment is resumed (adjacent fragment which are not visible can be in resumed state for example).

I am using ViewPager2 and the widget class.

edit

Maybe an alternative is use like a global layout change listener to test if the root layout of the fragment is 100% displayed?

1

There are 1 answers

1
Daniel Nugent On

It sounds like you should use a ViewPager2.OnPageChangeCallback

The onPageSelected() callback will be called when the page is selected, and you can base your logic on the position of the ViewPager.

viewPager.registerOnPageChangeCallback(
        object: ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                when (position) {
                    0 -> {
                        //Set button color
                    }
                    1 -> {
                        //Set button color to something else
                    }
                    else -> {

                    }
                }
            }
        }
)

If using the type of fragment currently showing would suit your needs better than using the position, you can use references to the fragments in the adapter, see here for more info: https://stackoverflow.com/a/36504458/4409409