Fragments in the viewpager only disappear after 2 turns

I'm having a weird issue with fragments inside a viewpager. If I rotate the device once everything seems to work and my fragments are loaded with all their data. However, on the second rotation, the fragments inside my viewer seem to disappear. If I check isAdded () it returns true, however isVisible () returns false. Is there a reason why the snippet will be added to my viewer but not displayed?

Here's my snippet that contains the viewer:

public class DrawerFragment extends ParentFragment{

ViewPager viewPager;

GradingFragmentPagerAdapter pagerAdapter;
ArrayList<ParentFragment> mGradingFragments;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    viewPager = (android.support.v4.view.ViewPager) rootView.findViewById(R.id.pager);
    if(mFragments == null){
     mFragments = new ArrayList<ParentFragment>();
     mFragments.add(new FragmentA());
     mFragments.add(new FragmentB());
    }
    pagerAdapter = new MyFragmentPager(getChildFragmentManager(), mFragments);
    viewPager.setAdapter(pagerAdapter);

    return rootView;
}

}

      

Here's my PagerAdapter class

 public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

    ArrayList<ParentFragment > fragments;

    public GradingFragmentPagerAdapter(android.support.v4.app.FragmentManager fm, ArrayList<ParentFragment> fragments){
        super(fm);
        this.fragments = fragments;
    }

    @Override
    public ParentFragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

}

      

What I don't understand is that it only seems to break in the second spin. If I set the background color on the viewpager, after two rotations, the area where my fragments should be is the background color in the view. However, if I look at it in debug mode, the fragment is added to the pagerAdapter. They are simply not visible.

Also it doesn't seem like onCreateView is getting called on 2 fragments inside the viewpager. I'm not entirely sure if this is the expected behavior or not when using setRetainInstance (true). From what I understand, setting it to the parent fragment should handle its child fragments as well. But isn't it necessary to recreate all kinds of child fragments every turn?

+3


source to share





All Articles