这次再对内容为View的ViewPager的适配器PagerAdapter进行简单的封装,支持List数据和SparseArray的数据,带更新视图功能。
首先,先贴上最上面的抽象类代码:
/* * Date: 14-8-18 * Project: Access-Control-V2 */ package cn.irains.access_control_v2.common; import android.support.v4.view.PagerAdapter; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import java.util.List; /** * 抽象的PagerAdapter实现类,封装了内容为View的公共操作. * Author: msdx ([email protected]) * Time: 14-8-18 下午2:34 */ public abstract class AbstractViewPagerAdapter extends PagerAdapter { protected SparseArray<View> mViews; public AbstractViewPagerAdapter() { mViews = new SparseArray<View>(); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public Object instantiateItem(ViewGroup container, int position) { View view = mViews.get(position); if (view == null) { view = newView(position); mViews.put(position, view); } container.addView(view); return view; } public abstract View newView(int position); public void notifyUpdateView(int position) { View view = updateView(mViews.get(position), position); mViews.put(position, view); notifyDataSetChanged(); } public View updateView(View view, int position) { return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(mViews.get(position)); } }
接下来看数据为List的封装,代码如下:
/* * Date: 14-8-18 * Project: Access-Control-V2 */ package cn.irains.access_control_v2.common; import android.view.View; import java.util.List; /** * 抽象的PagerAdapter实现类,封装了内容为View,数据为List类型的适配器实现. * Author: msdx ([email protected]) * Time: 14-8-18 下午2:34 */ public abstract class AbstractPagerListAdapter<T> extends AbstractViewPagerAdapter { protected List<T> mData; public AbstractPagerListAdapter(List<T> data) { mData = data; } @Override public int getCount() { return mData.size(); } public abstract View newView(int position); public T getItem(int position) { return mData.get(position); } }
同样,数据为SparseArray的适配器封装类代码与其相似,如下:
/* * Date: 14-8-18 * Project: Access-Control-V2 */ package cn.irains.access_control_v2.common; import android.util.SparseArray; import android.view.View; /** * 抽象的PagerAdapter实现类,封装了内容为View,数据为SparseArray类型的适配器实现. * Author: msdx ([email protected]) * Time: 14-8-18 下午2:34 */ public abstract class AbstractPagerSparseAdapter<T> extends AbstractViewPagerAdapter { protected SparseArray<T> mData; public AbstractPagerSparseAdapter(SparseArray<T> data) { mData = data; } @Override public int getCount() { return mData.size(); } public abstract View newView(int position); public T getItem(int position) { return mData.valueAt(position); } }