2

I have a TabLayout on my Activity with three tabs, each attached to a fragment fragment. These all load and work properly. My problem is when I try and replace one of these fragments at runtime.

By targeting the ViewPager (R.id.view_pager) object as the container, when I try and inflate the new fragment, both views disappear:

public void changeToNewFragment(){
    NewFragment newFragment = new NewFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.view_pager, newFragment).addToBackStack(null).commit();
}

If I try and target the entire view, with R.id.container, the new Fragment appears, overlaid on top of the current fragment:

public void changeToNewFragment(){
    NewFragment newFragment = new NewFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container, newFragment).addToBackStack(null).commit();
}

How do I inflate this new view, under the tabLayout, so that only this new view shows? This view should become part of the tabs, meaning if another tab is clicked, this view swipes away.

  • 1
    You can't do a FragmentTransaction on a ViewPager. You could [use nested fragments](http://stackoverflow.com/questions/7723964/replace-fragment-inside-a-viewpager), but personally I don't like that approach. I always use a second Activity for this sort of thing. Basically, create a second Activity that just has a FrameLayout that you use FragmentTransactions on. Whenever you want to navigate away from one of the ViewPager Fragments, just start the other Activity, and pass extras in the intent to tell it which Fragment to load. – Daniel Nugent Jun 08 '16 at 14:12
  • @DanielNugent If I create a second Activity, which seems to be the best option, how do I handle backStack? Should I just recreate the main activity from the second activity if (getFragmentManager().getBackStackEntryCount() == 0)? – Jacob Riedel Jun 08 '16 at 14:33
  • Take a look at the onBackPressed() override in this answer: http://stackoverflow.com/a/34026438 – Daniel Nugent Jun 08 '16 at 14:38

0 Answers0