今天做了个view pager动态删除,开始用了view形式,后来换成fragment,但是动态删除不了,viewpager中的view始终都在,后台查了下,找到了原因如下:
stackoverflow牛人的解决说明:
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.
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.
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。@Override
public int getItemPosition(Object object) {
// TODO Auto-generated method stub
return PagerAdapter.POSITION_NONE;
}
就是要实现FragmentStatePagerAdapter ,并overide上面这个方法。