这次再对内容为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 (645079761@qq.com) * 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)); } }
这里只对View相关的操作进行封装,不涉及任何数据,并增加了两个方法,一个是notifyUpdateView(int position),调用它之后将会去更新指定位置的视图。另一个方法是public View updateView(View view, int 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 (645079761@qq.com) * 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 (645079761@qq.com) * 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); } }
使用时,仅需要继承并实现newView(int position)方法即可。