0

I have a fragment "Fragment List" that contains Viewpager2.

When user clicks a button "Fragment List" will be replaced with "Fragment Form", after user finish updating the form. I will pop backstack the "Fragment Form". And the OnResume of "Fragment List" will be called

The problem is, NONE of the viewpager's fragment lifecycle gets called then how to tell the viewpager's fragment to update the data when "Fragment List" OnResume get called?

Please note that using interface may produce NullPointerException because when "Fragment List" OnResume get called, the viewpager may not ready yet

Thank you

Zain
  • 37,492
  • 7
  • 60
  • 84
Hal. ss
  • 63
  • 1
  • 11

1 Answers1

0

You can get the current page fragment of the ViewPager in the Fragment List fragment, and call a method directly on it to do your changes.

I assume that your ViewPager page fragment is named as PageFragment

add below in onResume() of the Fragment List fragment when you come back from Fragment Form

PageFragment fragment = (PageFragment) 
          mViewPagerAdapter.instantiateItem(mViewPager, mViewPager.getCurrentItem());
fragment.someMethod();  // pass your parameters

Create someMethod() method in the PageFragment, and pass it the parameters that you want to change there.

You also need to handle whether the onResume() of the Fragment List fragment gets called due to coming back from the Fragment Form or something else.

UPDATE

instantiateItem is not available. I am using Viewpager2, and ViewPagerAdapter which extends FragmentStateAdapter

You're right the above code works for ViewPager, and for ViewPager2 You can get the fragment of the current page with:

PagerFragment fragment = (PagerFragment)  getSupportFragmentManager()
                           .findFragmentByTag("f" + mViewPager.getCurrentItem());

then you can call some method on it.

fragment.someMethod();  // pass your parameters
Zain
  • 37,492
  • 7
  • 60
  • 84
  • Thank you for answering. But what is instantiateItem? Cause instantiateItem is not available. I am using Viewpager2, and ViewPagerAdapter which extends FragmentStateAdapter – Hal. ss Jul 25 '20 at 07:59
  • @Hal.ss thanks for the comment.. sorry for that I updated the answer in *UPDATE* section according to `ViewPager2` – Zain Jul 25 '20 at 14:37