Display fragment viewpager within a fragment

AndroidAndroid FragmentsAndroid ViewpagerAndroid LifecycleAndroid Nested-Fragment

Android Problem Overview


I have a fragment which contains a ViewPager. The ViewPager is associated with an adapter that contains a set of fragments.

Upon loading the parent fragment, I am met with an IllegalStateException with the message: java.lang.IllegalStateException: Recursive entry to executePendingTransactions.

Some research has led me to the conclusion that the system is unable display fragments within another fragment, HOWEVER there seems to be some indication that it is possible to do exactly this with the use of a ViewPager (A bug in ViewPager using it with other fragment).

In fact, if I add a button to my parent fragment which calls mPager.setAdapter(mAdapter) on my ViewPager when pressed, the ViewPager successfully loads. This is not ideal.

The issue then must be related to the fragment lifecycle. My question therefore, is this: Has anybody else found a way around this issue, and if so, how?

Is there some way to delay settings the adapter on the ViewPager until after the fragment transaction?

Here is my parent fragment code:

	@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	
	mView = inflater.inflate(R.layout.team_card_master, container, false);
	mViewPager = (ViewPager)mView.findViewById(R.id.team_card_master_view_pager);
	
	final Button button = (Button)mView.findViewById(R.id.load_viewpager_button);
	button.setOnClickListener(new OnClickListener() {
		@Override
		public void onClick(View v) {
			mViewPager.setAdapter(mAdapter);
			button.setVisibility(View.GONE);
		}
	});
	
	mAdapter = new ViewPagerAdapter(getFragmentManager());
 //		mViewPager.setAdapter(mAdapter);
	
	return mView;
}

And the adapter:

public class ViewPagerAdapter extends FragmentPagerAdapter {
	public ViewPagerAdapter(FragmentManager fm) {
		super(fm);
	}
	
	@Override
	public int getCount() {
		if (mCursor == null) return 0;
		else return mCursor.getCount();
	}
	
	@Override
	public Fragment getItem(int position) {
		Bundle b = createBundle(position, mCursor);
		return TeamCardFragment.newInstance(b);
	}
}

Android Solutions


Solution 1 - Android

use AsyncTask to set the adapter for viewPager. It works for me. The asyncTask is to make the original fragment complete it's transition. and then we proceed with viewPager fragments, basically to avoid recursion.

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

    mView = inflater.inflate(R.layout.team_card_master, container, false);
    mViewPager = (ViewPager)mView.findViewById(R.id.team_card_master_view_pager);

    final Button button = (Button)mView.findViewById(R.id.load_viewpager_button);
    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mViewPager.setAdapter(mAdapter);
            button.setVisibility(View.GONE);
        }
    });

    mAdapter = new ViewPagerAdapter(getFragmentManager());
    new setAdapterTask().execute();

    return mView;
}

private class setAdapterTask extends AsyncTask<Void,Void,Void>{
      protected Void doInBackground(Void... params) {
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
                   mViewPager.setAdapter(mAdapter);
		}
}

Solution 2 - Android

You can use FragmentStatePagerAdapter instead of FragmentPageAdapter. It will remove fragments for you.

Solution 3 - Android

I just ran into this same problem. I had a Fragment that needed to host a ViewPager of Fragments. When I stacked another Fragment on top of my ViewPagerFragment, and then hit back, I would get an IllegalStateException. After checking the logs (when stacking a new Fragment), I found that my ViewPagerFragment would go through its lifecycle methods to stop and destroy, however its children Fragments in the the ViewPager would stay in onResume. I realized that the children Fragments should be managed by the FragmentManager for the ViewPagerFragment, not the FragmentManager of the Activity.

I understand at the time, the answers above were to get around the limitations of Fragments not being able to have children Fragments. However, now that the latest support library has support for Fragment nesting, you no longer need to hack around setting the adapter for your ViewPager, and passing getChildFragmentManager() is all you need. This has been working perfectly for me so far.

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

    mView = inflater.inflate(R.layout.team_card_master, container, false);
    mViewPager = (ViewPager) mView.findViewById(R.id.team_card_master_view_pager);

    mAdapter = new ViewPagerAdapter(getChildFragmentManager());
    mViewPager.setAdapter(mAdapter);

    return mView;
}

Solution 4 - Android

I used Handler.post() to set adapter outside of original fragment transaction:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            mViewPager.setAdapter(mAdapter);     
        }
    });        
}

Solution 5 - Android

I have faced this problem when trying to initialize the viewPager adapter on the TabIndicator in on ViewCreated. After reading about it online I realised that this could be just because the fragment was not yet added to the activity. So I moved the initialization code to onStart() of the fragment, this should solve your problem. But not for me I still was getting same issue again.

But that was because in my code I was trying the bypass the normal async execution of pending task by explicitly call to executePendingTransactions(), after blocking that everything worked well

Solution 6 - Android

> Upon loading the parent fragment, I am met with an IllegalStateException with the message: java.lang.IllegalStateException: Recursive entry to executePendingTransactions.

Some research has led me to the conclusion that the system is unable display fragments within another fragment, HOWEVER there seems to be some indication that it is possible to do exactly this with the use of a ViewPager (A bug in ViewPager using it with other fragment).

set Id for ViewPager explicitly.

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      mView = inflater.inflate(R.layout.team_card_master, container, false);
      mViewPager = (ViewPager)mView.findViewById(R.id.team_card_master_view_pager);
      mViewPager.setId(100);

      final Button button = (Button)mView.findViewById(R.id.load_viewpager_button);
      button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
          mViewPager.setAdapter(mAdapter);
          button.setVisibility(View.GONE);
        }
      });
      mAdapter = new ViewPagerAdapter(getFragmentManager());
      mViewPager.setAdapter(mAdapter);

      return mView;
    }

You can use id in your xml resources instead of a magic number 100.

<resources>
  <item name="Id_For_ViewPager" type="id"/>
</resources>

and setId(R.Id_For_ViewPager).

See FragmentManager.java source for more detail.

https://github.com/android/platform_frameworks_support/blob/master/v4/java/android/support/v4/app/FragmentManager.java#L900

Or see this page(Japanese). The original idea is from her, actually, not me. http://y-anz-m.blogspot.jp/2012/04/androidfragment-viewpager-id.html

Solution 7 - Android

Using this brilliant post by Thomas Amssler : http://tamsler.blogspot.nl/2011/11/android-viewpager-and-fragments-part-ii.html

Iv'e created a adapter that can be used to create all types of fragments. The adapter itself look like this :

public abstract class EmbeddedAdapter extends FragmentStatePagerAdapter {

private SparseArray<WeakReference<Fragment>>	mPageReferenceMap	= new SparseArray<WeakReference<Fragment>>();
private ArrayList<String> mTabTitles;

public abstract Fragment initFragment(int position);

public EmbeddedAdapter(FragmentManager fm, ArrayList<String> tabTitles) {
	super(fm);
	mTabTitles = tabTitles;
}

@Override
public Object instantiateItem(ViewGroup viewGroup, int position) {
	mPageReferenceMap.put(Integer.valueOf(position), new WeakReference<Fragment>(initFragment(position)));
	return super.instantiateItem(viewGroup, position);
}

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

@Override
public CharSequence getPageTitle(int position) {
	return mTabTitles.get(position);
}

@Override
public Fragment getItem(int pos) {
	return getFragment(pos);
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
	super.destroyItem(container, position, object);
	mPageReferenceMap.remove(Integer.valueOf(position));
}

public Fragment getFragment(int key) {

	WeakReference<Fragment> weakReference = mPageReferenceMap.get(key);

	if (null != weakReference) {

		return (Fragment) weakReference.get();

	} else {
		return null;
	}
}

@Override
public int getItemPosition(Object object) {
	return POSITION_NONE;
}

}

To use the adapter you will have to do the following :

private void setAdapter() {
	
	if(mAdapter == null) mAdapter = new EmbeddedAdapter(getActivity().getSupportFragmentManager(), mTabTitles) {

		@Override
		public Fragment initFragment(int position) {
		
			Fragment fragment;

			if(position == 0){
				
				// A start fragment perhaps?
				fragment = StartFragment.newInstance(mBlocks);
				
			}else{
				
				// Some other fragment
				fragment = PageFragment.newInstance(mCategories.get((position)));
			}
			return fragment;
		}
	};

	// Have to set the adapter in a handler
	Handler handler = new Handler();
	handler.post(new Runnable() {

		@Override
		public void run() {

			mViewPager.setVisibility(View.VISIBLE);
			mPagerTabStrip.setVisibility(View.VISIBLE);
			mAdapter.notifyDataSetChanged();
		}
	});
}

Note that all the fragments use the :

setRetainInstance(true);

Solution 8 - Android

According with the documentation: https://developer.android.com/reference/android/app/Fragment.html#getChildFragmentManager()

If you want to manage the nesting fragment you must use getChildFragmentManager instead of getFragmentManager.

Solution 9 - Android

Instead of setting the adapter in AsyncTask or any Handler just write that part of code in onResume() section

Doing Such you will:

  • Let the transition of the main fragment to complete.
  • Display the child fragment without use of any background task.

The code of onResume() is as follows in your case:

@Override
public void onResume() {
    super.onResume();
    if(mViewPager.getAdapter()==null||mViewPager.getAdapter().getCount()==0)
    mViewPager.setAdapter(mAdapter);
}

Also in onCreateView Instead of

mAdapter = new ViewPagerAdapter(getFragmentManager());

Replace with

mAdapter = new ViewPagerAdapter(getChildFragmentManager());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhowettlView Question on Stackoverflow
Solution 1 - AndroidYashwanth KumarView Answer on Stackoverflow
Solution 2 - AndroidLeszekView Answer on Stackoverflow
Solution 3 - AndroidSteven ByleView Answer on Stackoverflow
Solution 4 - AndroidinazarukView Answer on Stackoverflow
Solution 5 - AndroidSanketView Answer on Stackoverflow
Solution 6 - AndroidKugyoView Answer on Stackoverflow
Solution 7 - AndroidSlickelitoView Answer on Stackoverflow
Solution 8 - AndroidSalvatore CozzuboView Answer on Stackoverflow
Solution 9 - AndroidKaranView Answer on Stackoverflow