Search code examples
androidandroid-fragmentsfragmenttransactionfragmentstatepageradapter

How to replace fragment from ViewPager with a new one


I found so many similar questions and so many different answers, but none of them helped me. I will try to post a clear question to get a clear answer if it's possible.

So I have an Activity that has a ViewPager with FragmentStatePagerAdapter containing (for now) only one fragment (HomeScreenFragment).

Inside HomeScreenFragment I have a RecyclerView with a list of several kind of different icons which should open a different fragment for each item click.

HomeScreenFragment has a FrameLayout as a root layout with id name "container". This is the method I'm calling to replace HomeScreenFragment with MainTypesFragment in this case:

 private void openAllTypesFragment() {
    MainTypesFragment fragment = new MainTypesFragment();
    FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.container, fragment);
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    transaction.addToBackStack(HomeScreenFragment.class.getName());
    transaction.commit();
    eventBus.post(new Event(null, Event.EVENT_FRAGMENT));
}

Since FragmentStatePagerAdapter is initialized in MainActivity, I'm sending an event which will MainActivity catch and call adapter.notifyDataSetChanged();

Doing it this way, nothing happens.. I tried with getChildFragmentManager() instead of getActivity().getSupportFragmentManager() and in that case, previous fragment (HomeScreenFragment) is visible underneath new one (MainTypesFragment)..

Any ideas what am I doing wrong here?


Solution

  • The container you are using is wrong.Maintain one container in the activity xml and use that container to load all the fragments.

    transaction.replace(R.id.container, fragment);
    

    The container here is to be the activity container in which viewpager and other views should be present.