Android: Viewpager and FragmentStatePageAdapter

后端 未结 5 1187
春和景丽
春和景丽 2021-02-04 15:05

I\'m designing an app that allows users to flip between multiple pages in a ViewPager. I\'ve been struggling trying to figure out how it is possible to remove a Fragment instan

5条回答
  •  独厮守ぢ
    2021-02-04 15:55

    Here's an example of how I implemented caching in PagerAdapter. After filling the cache all future view requests are served from cache, only data is replaced.

    public class TestPageAdapter extends PagerAdapter{
    
    private int MAX_SIZE = 3;
    private ArrayList> pageCache = new ArrayList>(3);
    
    
    public TestPageAdapter(Context context){
        // do some initialization
    }
    
    @Override
    public int getCount() {
        // number of pages
    }
    
    private void addToCache(View view){
        if (pageCache.size() < MAX_SIZE){
            pageCache.add(new SoftReference(view));
        } else {
            for(int n = (pageCache.size()-1); n >= 0; n--) {
                SoftReference cachedView = pageCache.get(n);
                if (cachedView.get() == null){
                    pageCache.set(n, new SoftReference(view));
                    return;
                }
            }
        }
    }
    
    private View fetchFromCache(){
        for(int n = (pageCache.size()-1);  n>= 0; n--) {
            SoftReference reference = pageCache.remove(n);
            View view = reference.get();
            if (view != null) {
                return view;
            }
        }
        return null;
    }
    
    @Override
    public Object instantiateItem(View collection, int position) {
        View view = fetchFromCache();
        if (view == null) {
            // not in cache, inflate manually
            LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.page, null);
        } 
        setData(view, position);
        ((ViewPager) collection).addView(view, 0);
        return view;         
    }
    
    private void setData(View view, int position){
        // set page data (images, text ....)
    }
    
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        currentItem = (View)object;
    }
    
    public View getCurrentItem() {
        return currentItem;
    }
    
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((View) object);
    }
    
    @Override
    public void destroyItem(View collection, int arg1, Object view) {
        ((ViewPager) collection).removeView((View) view);
        addToCache((View) view);
    }
    
    }
    

提交回复
热议问题