fragments when used with ViewPager2 is not geting visible(STARTED) prior I add any view to any of the Fragment

35 Views Asked by At

My application works on an InstructionSet model. In layman's terms, I call a set of functions in a sequence on MainThread to draw on screen.

To create a carousel View, I'm calling the below functions:

  1. fun ZoneOperation (): Creates a RelativeLayout, a Viewpager2 and FragmentStateAdapter instances and add Fragments(containing a RelativeLayout) to it.
  2. fun ButtonOperation (): Add a button to one of the fragments(In its RelativeLayout) created and added to the viewpager2 above.

Now, before my fragments are visible to the user (onStart()), the ButtonOperation () function is getting called and is trying to find the RelativeLayout of the Fragment to create and add a button to it, but since the RelativeLayout itself isn't created yet my application crashes.

I understand Fragment Lifecycle, that in onCreateView() we initiate the RelativeLayout instance and after onStart() the RelativeLayout is visible and can be accessed by findViewById() to add button.

I get that when we commit a FragmentTransaction, The commit does not happen immediately. it will be scheduled as work on the main thread to be done the next time that thread is ready and we can use commitNow to add the fragment immediately.

but In case of Viewpager2 and not creating any FragmentTransaction but only adding the Fragment to the adapter and internally it is handling the transactions and even though the FragmentStateAdapter is internally using commitNow in its method onViewAttachedToWindow still my Fragment is not getting available immediately before ButtonOperation get called.

Is there a way to fix this?

0

There are 0 best solutions below