Android万能适配器基类

来源:互联网 发布:php建行支付接口demo 编辑:程序博客网 时间:2024/05/16 16:08

在Android开发中,我们经常需要使用适配器来显示数据,如果我们每次都让当前的适配器去继承BaseAdapter,然后重写它的几个方法,会不会觉得很麻烦呢,下面给大家介绍一个适配器基类,可以说是万能的,我们只需要去关心getView方法就可以了。

public abstract class BaseListAdapter<T> extends BaseAdapter {    protected final String TAG = this.getClass().getSimpleName();    //context对象    protected Context mContext;    //数据集合    protected List<T> mValues;    //布局填充器    protected LayoutInflater mInflater;    public BaseListAdapter(Context context, List<T> values) {        mContext = context;        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);        mValues = values;    }    /**     * 获取上下文对象     * @return     */    public Context getContext() {        return mContext;    }    /**     * 获取数据量     * @return     */    @Override    public int getCount() {        if (mValues != null){         return mValues.size();        }        return 0;    }    /**     * 获取当前对象     * @param position     * @return     */    @Override    public T getItem(int position) {        if (position == getCount()  || mValues == null) {            return null;        }        return mValues.get(position);    }    @Override    public long getItemId(int position) {        return position;    }    /**     * 显示当前视图     * @param position     * @param convertView     * @param parent     * @return     */    @Override    public View getView(int position, View convertView, ViewGroup parent) {        return getItemView(convertView, position);    }    protected abstract View getItemView(View convertView, int position);    /**     * 更新数据     * @param values     */    public void update(List<T> values) {        mValues = values;        notifyDataSetInvalidated();        notifyDataSetChanged();    }}
0 0