Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android getParentFragment() returns null in ViewPager within a Fragment

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.

like image 724
Thomas Vos Avatar asked Oct 29 '22 18:10

Thomas Vos


1 Answers

In my case , I was using FragmentManager instead of ChildFragmentManager which was causing this issue.

like image 84
user2991413 Avatar answered Nov 11 '22 12:11

user2991413