I have an Activity
that contains a Fragment
with a ViewPager
. Then I call a method of a Fragment
within the ViewPager. But if that Fragment then calls getParentFragment()
, it returns null.
Why is getParentFragment()
null?
The main Fragment that contains a ViewPager:
public class MyFragment extends Fragment {
private TabLayout mTabLayout;
private ViewPager mViewPager;
private ViewPagerAdapter mAdapter;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View view = getView();
// Setup the ViewPager
mViewPager = (ViewPager) view.findViewById(R.id.container);
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager(), getActivity());
mViewPager.setAdapter(adapter);
//setupViewPager(mViewPager);
// Setup the TabLayout
mTabLayout = (TabLayout) view.findViewById(R.id.tabs);
mTabLayout.setupWithViewPager(mViewPager);
}
// This method is called from Activity.
public void callNestedFragment() {
if (isDetached()) {
return;
}
// This fragment cannot be null, because it doesn't crash here. (this is just a sample).
((Fragment0) mViewPager.getItem(0)).testMethod();
}
}
The nested Fragment (inside mViewPager
):
public class Fragment0 extends Fragment {
...
public void testMethod() {
if (isDetached()) {
return;
}
// Why is getParentFragment() null? This is the log: "Parent fragment: null"
Log.i(TAG, "Parent fragment: " + getParentFragment());
return;
}
}
The ViewPagerAdapter
:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private Context mContext;
public ViewPagerAdapter(FragmentManager manager, Context context) {
super(manager);
mContext = context;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment0();
case 1:
return new Fragment1();
case 2:
return new Fragment2();
case 3:
return new Fragment3();
case 4:
return new Fragment4();
}
return null;
}
@Override
public int getCount() {
return 5;
}
}
If more code is needed, please let me know. Thanks for your help.
In my case , I was using FragmentManager instead of ChildFragmentManager which was causing this issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With