• FragmentStatePagerAdapter的使用


    1、两点

    getItemPosition的覆写使notifyDataSetChanged();会根据数据源的变动更新,不过是全部重新加载,和ListView不一样

    为了从外界(Activity)操作当前的fragment界面,使用了SparseArray<WeakReference<Fragment>>将当前的fragment实例存起来。

    public class WillPagerAdapter extends FragmentStatePagerAdapter {
        // SparseArray是Hashmap的改良品,其核心是折半查找函数(binarySearch)
        SparseArray<WeakReference<Fragment>> registeredFragments = new SparseArray<WeakReference<Fragment>>();
        private List<Will> mList;
    
    
        public WillPagerAdapter(FragmentManager fm) {
            super(fm);
        }
    
        public WillPagerAdapter(FragmentManager fm, List<Will> list) {
            this(fm);
            // TODO Auto-generated constructor stub
            mList = list;
        }
    
        /*
         * 生成新的 Fragment 对象。 .instantiateItem() 在大多数情况下,都将调用 getItem() 来生成新的对象
         */
        @Override
        public Fragment getItem(int position) {
            // TODO Auto-generated method stub
            WillFragment fragment = WillFragment.newInstance(mList.get(position));
            return fragment;
        }
    
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // TODO Auto-generated method stub
            // 得到缓存的fragment
            WillFragment fragment = (WillFragment) super.instantiateItem(container,
                    position);
            WeakReference<Fragment> weak = new WeakReference<Fragment>(fragment);
            registeredFragments.put(position, weak);
            return fragment;
        }
    
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mList.size();
        }
    
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            registeredFragments.remove(position);
    
            super.destroyItem(container, position, object);
    
        }
    
        /**
         * 要求getItemPosition、FragmentStatePagerAdapter
         */
        public void remove(int position) {
            mList.remove(position);
            notifyDataSetChanged();
        }
    
        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }public WillFragment getRegisteredFragment(int position) {
            return (WillFragment) registeredFragments.get(position).get();
        }
    }

    Done

  • 相关阅读:
    [cf621E]Wet Shark and Blocks
    [学习笔记]数论
    [CZYZ2016]day8
    Python 对 Excel 操作用法详解
    HTML学记笔记
    Django 2.2_错误:UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal multibyte sequence
    Python在终端通过pip安装好包以后,在Pycharm中依然无法使用的解决办法
    div的移动特效
    jQuery各种动画效果
    jqZoom插件
  • 原文地址:https://www.cnblogs.com/xingyyy/p/4348991.html
Copyright © 2020-2023  润新知