There are ViewPager, ViewPagerAdapter,TabLayout and three fragments Fagment1, Fragment2, Fragment3 . ViewPager displays 2 fragments.

 ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); ViewPagerAdapter mVPAdapter = new ViewPagerAdapter(getSupportFragmentManager()); mVPAdapter.addFrag(new Fragment_1(), ""); mVPAdapter.addFrag(new Fragment_2(), ""); viewPager.setAdapter(mVPAdapter); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); 

How to replace Fragment 1 by 3 dynamically?

    1 answer 1

    1. Create a fragment replacement method in the adapter.
    2. Make the adapter extend the FragmentStatePagerAdapter
    3. Immediately after replacing the fragment, call mVPAdapter.notifyDataSetChanged()
    4. Add this method to the adapter:

       @Override public int getItemPosition(Object object) { return POSITION_NONE; } 
    • I understand that I will need to use a FragmentStatePagerAdapter instead of a ViewPagerAdapter? - Igor
    • @Igor, yes, that's right - YuriySPb
    • @Igor, there are a lot of nuances. I use the proposed and it works for me. Before that, he used others and they only worked with props from a variety of crutches. - Yuriy SPb
    • 1. When you write - "fragment replacement method", what do you mean? My fragments are stored: List <Fragment> mFragmentList = new ArrayList <> (); I wrote a fragment replacement method in this ArrayList: public void replaceFrag (int position, Fragment fragment) {mFragmentList.set (position, fragment); } By pressing a button, I call it. mVPAdapter.replaceFrag (0, new Fragment_03 ()); mVPAdapter.notifyDataSetChanged (); But the first fragment does not change. - Igor
    • one
      Thank! All OK. - Igor