ViewPager fragment loads even if the parent Fragment is not active

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-05 07:04:27

问题


The background

I have single activity in my App which loads 2 fragments based on some menu item selection

public class ActivityMain extends AppCompatActivity{
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(savedInstanceState == null) {
            loadFragment(1); // DEFAULT FRAGMENT, AT THE BEGINNING
        }
    }
    ..........................
    ..........................
    // This method is called above, ALSO onItemClick in the Navigation Drawer (code not included for brevity)
    public void loadFragment(int position) {
        Fragment fragment = null;
        switch (position) {
            case 1:
                fragment = new Fragment1();
                break;
            case 2:
                fragment = new Fragment2();
                break;
            default:
                break;
        }
        if (fragment != null) {
            getFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment, "frag_" + position).addToBackStack(null).commit();
        }
    }
}

"Fragment1" is a simple fragment with a fixed text in a TextView. "Fragment2" uses SlidingTabLayout to load a Fragment "FragmentViewPager" in a viewpager using FragmentStatePagerAdapter.

The issue I am facing:

Even if I remove "Fragment2" from the Activity's Frame Layout (using getFragmentManager().beginTransaction().remove), Fragment "FragmentViewPager" does not get destroyed, rather it resumes every time Activity resumes.

Question

Why FragmentViewPager is not destroyed with "Fragment2"?


回答1:


If you are using FragmentStatePagerAdapter then this will not destroy fragment and when you swipe and come back to that fragment it will show old data without refresh. Because of not destroyed by viewpager.



来源:https://stackoverflow.com/questions/41412926/viewpager-fragment-loads-even-if-the-parent-fragment-is-not-active

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!