简体   繁体   中英

TabLayout ViewPager Clear Fragment

I have a TabLayout with a ViewPager . The ViewPager has two tab items A and B.

When I hit tab A it shows me the correct view, same for tab B. Now in Tab A, I display a few Fragment 's A1(default)->A2->A3. When I hit tab B and then come back to Tab A, I can still see A3. How can I go to Fragment A1 each time I hit Tab A? I'm not sure where to add this logic ( ViewPager or on the TabLayout.ViewPagerOnTabSelectedListener ) and default to the A1 Fragment .

Any ideas?

From A1>A2>A3 this is the way I'm replacing the fragments.

just call the replace fragment with same container of all three fragments.

public void replaceFragment(Fragment fragment, int container, String tag) {
    mFragmentManager = getFragmentManager();
    mFragmentTransaction = mFragmentManager.beginTransaction();
    mFragmentTransaction.replace(containerId, fragment, tag);
    mFragmentTransaction.addToBackStack(tag);
    mFragmentTransaction.commit();
}

And for back press button : remove fragment this way

public void removeFragment() {
    mFragmentManager = getFragmentManager();
    mFragmentManager.popBackStack();
}

Here whenever you go to B tab and come back to A, state of fragment A3 is destroyed, hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM