Below is my code which has 3 Fragment classes
each embedded with each of the 3 tabs on ViewPager
. I have a menu option. As shown in the onOpt
I tried the following:
int index = mViewPager.getCurrentItem();
List<Fragment> fragments = getSupportFragmentManager().getFragments();
View rootView = fragments.get(index).getView();
After reading all comments and answers I am going to explain an optimal solution for this problem. The best option is @rik's solution, so my improvement is base on his.
Instead of having to ask each FragmentClass like
if(FragmentClass1){
...
if(FragmentClass2){
...
}
Create your own interface, and maker your child fragments implement it, something like
public interface MyChildFragment {
void updateView(int position);
}
Then, you can do something like this to initiate and update your inner fragments.
Fragment childFragment = (Fragment) mViewPagerDetailsAdapter.instantiateItem(mViewPager,mViewPager.getCurrentItem());
if (childFragment != null) {
((MyChildFragment) childFragment).updateView();
}
P.S. Be careful where you put that code, if you call insatiateItem before the system actually create it the savedInstanceState
of your child fragment will be null therefor
public void onCreate(@Nullable Bundle savedInstanceState){
super(savedInstanceState)
}
Will crash your app.
Good luck
public class MyPagerAdapter extends FragmentPagerAdapter {
private Fragment mCurrentFragment;
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
//...
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (getCurrentFragment() != object) {
mCurrentFragment = ((Fragment) object);
}
super.setPrimaryItem(container, position, object);
}
}
You can implement a BroadcastReceiver in the Fragment and send an Intent from anywhere. The fragment's receiver can listen for the specific action and invoke the instance's method.
One caveat is making sure the View component is already instantiated and (and for some operations, such as scrolling a list, the ListView must already be rendered).
getSupportFragmentManager().getFragments().get(viewPager.getCurrentItem());
Cast the instance retreived from above line to the fragment you want to work on with. Works perfectly fine.
viewPager
is the pager instance managing the fragments.
Best way to do this, just call CallingFragmentName fragment = (CallingFragmentName) viewPager .getAdapter() .instantiateItem(viewPager, viewPager.getCurrentItem()); It will re-instantiate your calling Fragment, so that it will not throw null pointer exception and call any method of that fragment.