Skip to content Skip to sidebar Skip to footer

Pager Inside A Fragment

As mentioned in my previous question I had some problem with showing Fragments inside a ViewPager after opening another Fragment from one of the Fragments inside the ViewPager. I s

Solution 1:

What do you want to do exactly? Are you trying to replace a Fragment inside the ViewPager? Or are you trying to replace a Fragment inside a Fragment inside the ViewPager? Or are you trying to do something different altogether? I can only give you an accurate solution if you explain what you are trying to do in detail. Anyway here is what I am guessing might be wrong:


I think your problem is that you use the wrong FragmentManager. There are multiple different FragmentManagers, but essentially there are two cases:

  1. You want to add/replace/remove a Fragment from an Activity
  2. You want to add/replace/remove a Fragment from another Fragment

As long as I don't see your layout files I can't be sure which of those two options fits your situation.


Solution if you want to replace a Fragment inside of another Fragment

If you want to perform a FragmentTransaction on a Fragment inside of another Fragment, then you need to use the child FragmentManager! You can use the child FragmentManager inside a Fragment like this:

FragmentManagerfragmentManager= getChildFragmentManager();
FragmentTransactiontransaction= fragmentManager.beginTransaction();
transaction.replace(R.id.content_frame, fragment);
fragment.setRetainInstance(true);
transaction.addToBackStack(null);
transaction.commit();

As you can see you just need to use getChildFragmentManager() instead of getSupportFragmentManager()


As I already said, without any further information about your situation I cannot give you a more accurate answer. So please try to explain what you want to do as best as you can to me and I'm confident we can solve this.

Solution 2:

Finally i found what i did wrong in my code :

i'm using this below code for setting adapter for view Pager inside a fragment :

  adapter = newMyAdapter(getFragmentManager());
            pager = (ViewPager) rootView.findViewById(R.id.pager);
            pager.setAdapter(adapter);

and by replacing getFragmentManager() to getChildFragmentManager() we resolve this problem. As per my understanding i'm using view pager inside a fragment that's why i have to use getChildFragment manager to store transitions of my viewPager. Might this help someone and this question is still open for better solutions.

Post a Comment for "Pager Inside A Fragment"