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