android – call next fragment's lifecycle method when use viewpager2 with TabLayoutMediator-ThrowExceptions

Exception or error:

I use Viewpager2 With setup tablayout using TabLayoutMediator but the issue is
when I swipe viewpager first fragment to the second fragment here only call
current fragment’s lifecycle methods, but when I click on tablayout
then call next fragment’s lifecycle methods. I don’t know why this happens?

How to solve:

This happens because the method that TabLayoutMediator uses to move to the selected fragment causes the RecyclerView to cache the next Fragment as it uses Smooth Scrolling.

This should not be a problem UNLESS you are doing something in the wrong part of the Fragment’s lifecycle. If you only want do something when a Fragment is displayed then only do it in the Fragments onResume method as the behaviour you describe will only take the cached Fragment to “Started” state.

Leave a Reply

Your email address will not be published. Required fields are marked *