Remove Fragment Page from ViewPager in Android

前端 未结 17 1161
庸人自扰
庸人自扰 2020-11-22 17:20

I\'m trying to dynamically add and remove Fragments from a ViewPager, adding works without any problems, but removing doesn\'t work as expected.

Everytime I want to

17条回答
  •  伪装坚强ぢ
    2020-11-22 17:43

    The ViewPager doesn't remove your fragments with the code above because it loads several views (or fragments in your case) into memory. In addition to the visible view, it also loads the view to either side of the visible one. This provides the smooth scrolling from view to view that makes the ViewPager so cool.

    To achieve the effect you want, you need to do a couple of things.

    1. Change the FragmentPagerAdapter to a FragmentStatePagerAdapter. The reason for this is that the FragmentPagerAdapter will keep all the views that it loads into memory forever. Where the FragmentStatePagerAdapter disposes of views that fall outside the current and traversable views.

    2. Override the adapter method getItemPosition (shown below). When we call mAdapter.notifyDataSetChanged(); the ViewPager interrogates the adapter to determine what has changed in terms of positioning. We use this method to say that everything has changed so reprocess all your view positioning.

    And here's the code...

    private class MyPagerAdapter extends FragmentStatePagerAdapter {
    
        //... your existing code
    
        @Override
        public int getItemPosition(Object object){
            return PagerAdapter.POSITION_NONE;
        }
    
    }
    

提交回复
热议问题