RecyclerAdapter基类

BaseViewHolder.java
/**
 * 类说明:复用ViewHolder, 绑定 RecyclerView item 的控件
 * Author: gaobaiq
 * Date: 2016/3/29 16:02
 */
public class BaseViewHolder {

    private SparseArray<View> mViews;
    private View view;

    public static BaseViewHolder getViewHolder(View view) {
        BaseViewHolder baseViewHolder = (BaseViewHolder) view.getTag();
        if (baseViewHolder == null) {
            baseViewHolder = new BaseViewHolder(view);
            view.setTag(baseViewHolder);
        }
        return baseViewHolder;
    }

    private BaseViewHolder(View view) {
        this.view = view;
        mViews = new SparseArray<>();
        view.setTag(mViews);
    }

    public <T extends View> T get(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = this.view.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    public View getConvertView() {
        return view;
    }

    /**
     * 关于值的设置
     */
    public BaseViewHolder setText(int viewId, String text) {
        TextView tv = get(viewId);
        tv.setText(text);
        return this;
    }

    public BaseViewHolder setImageResource(int viewId, int resId) {
        ImageView view = get(viewId);
        view.setImageResource(resId);
        return this;
    }

    public BaseViewHolder setImageBitmap(int viewId, Bitmap bitmap) {
        ImageView view = get(viewId);
        view.setImageBitmap(bitmap);
        return this;
    }

    public BaseViewHolder setImageDrawable(int viewId, Drawable drawable) {
        ImageView view = get(viewId);
        view.setImageDrawable(drawable);
        return this;
    }

    public BaseViewHolder setBackgroundColor(int viewId, int color) {
        View view = get(viewId);
        view.setBackgroundColor(color);
        return this;
    }

    public BaseViewHolder setBackgroundRes(int viewId, int backgroundRes) {
        View view = get(viewId);
        view.setBackgroundResource(backgroundRes);
        return this;
    }

    public BaseViewHolder setTextColor(int viewId, int textColor) {
        TextView view = get(viewId);
        view.setTextColor(textColor);
        return this;
    }

    @SuppressLint("NewApi")
    public BaseViewHolder setAlpha(int viewId, float value) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            get(viewId).setAlpha(value);
        } else {
            // Pre-honeycomb hack to set Alpha value
            AlphaAnimation alpha = new AlphaAnimation(value, value);
            alpha.setDuration(0);
            alpha.setFillAfter(true);
            get(viewId).startAnimation(alpha);
        }
        return this;
    }

    public BaseViewHolder setVisible(int viewId, boolean visible) {
        View view = get(viewId);
        view.setVisibility(visible ? View.VISIBLE : View.GONE);
        return this;
    }

    public BaseViewHolder setVisible(int viewId, int visible) {
        View view = get(viewId);
        view.setVisibility(visible);
        return this;
    }

    public BaseViewHolder linkify(int viewId) {
        TextView view = get(viewId);
        Linkify.addLinks(view, Linkify.ALL);
        return this;
    }

    public BaseViewHolder setTypeface(Typeface typeface, int... viewIds) {
        for (int viewId : viewIds) {
            TextView view = get(viewId);
            view.setTypeface(typeface);
            view.setPaintFlags(view.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
        }
        return this;
    }

    public BaseViewHolder setProgress(int viewId, int progress) {
        ProgressBar view = get(viewId);
        view.setProgress(progress);
        return this;
    }

    public BaseViewHolder setProgress(int viewId, int progress, int max) {
        ProgressBar view = get(viewId);
        view.setMax(max);
        view.setProgress(progress);
        return this;
    }

    public BaseViewHolder setMax(int viewId, int max) {
        ProgressBar view = get(viewId);
        view.setMax(max);
        return this;
    }

    public BaseViewHolder setRating(int viewId, float rating) {
        RatingBar view = get(viewId);
        view.setRating(rating);
        return this;
    }

    public BaseViewHolder setRating(int viewId, float rating, int max) {
        RatingBar view = get(viewId);
        view.setMax(max);
        view.setRating(rating);
        return this;
    }

    public BaseViewHolder setTag(int viewId, Object tag) {
        View view = get(viewId);
        view.setTag(tag);
        return this;
    }

    public BaseViewHolder setTag(int viewId, int key, Object tag) {
        View view = get(viewId);
        view.setTag(key, tag);
        return this;
    }

    public BaseViewHolder setChecked(int viewId, boolean checked) {
        Checkable view = get(viewId);
        view.setChecked(checked);
        return this;
    }

}
RecyclerViewHolder.java
/**
 * 类说明:
 * Author: gaobaiq
 * Date: 2016/3/29 16:20
 */
public class RecyclerViewHolder extends RecyclerView.ViewHolder {

    private BaseViewHolder baseViewHolder;

    public RecyclerViewHolder(View itemView) {
        super(itemView);
        baseViewHolder = BaseViewHolder.getViewHolder(itemView);
    }

    public BaseViewHolder getViewHolder() {
        return baseViewHolder;
    }
}
CommonRecyclerAdapter.java
/**
 * 类说明:RecyclerView 适配器基类
 * Author: gaobaiq
 * Date: 2016/3/29 15:58
 */
public abstract class CommonRecyclerAdapter<T> extends RecyclerView.Adapter<RecyclerViewHolder> {

    protected Context mContext;
    protected List<T> mList;

    protected ViewHolderClick<T> holderClick;
    protected AdapterView.OnItemClickListener onItemClickListener;
    protected AdapterView.OnItemLongClickListener onItemLongClickListener;

    public CommonRecyclerAdapter(Context context) {
        this.mContext = context;
        this.mList = new ArrayList<>();
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(onCreateViewLayoutID(viewType), parent, false);
        return new RecyclerViewHolder(view);
    }

    @Override
    public void onViewRecycled(final RecyclerViewHolder holder) {
        super.onViewRecycled(holder);
    }

    @Override
    public void onBindViewHolder(final RecyclerViewHolder holder, final int position) {
        onBindViewHolder(holder.getViewHolder(), position);
        if (onItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onItemClickListener.onItemClick(null, v, holder.getAdapterPosition(), holder.getItemId());
                }
            });
        }

        if (onItemLongClickListener != null) {
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    onItemLongClickListener.onItemLongClick(null, v, holder.getAdapterPosition(), holder.getItemId());
                    return false;
                }
            });
        }
    }

    public abstract int onCreateViewLayoutID(int viewType);

    public abstract void onBindViewHolder(BaseViewHolder holder, int position);

    @Override
    public int getItemCount() {
        return mList == null ? 0 : mList.size();
    }

    /**
     * 获取列表
     */
    public List<T> getList() {
        return mList;
    }

    /**
     * 替换某一个元素
     */
    public void replaceBean(int position, T t) {
        if (t != null) {
            this.mList.remove(position);
            this.mList.add(position, t);
            notifyItemChanged(position, t);
        }
    }

    /**
     * 添加数据列表到列表头部
     */
    public void addListAtStart(List<T> list) {
        if (list != null && !list.isEmpty()) {
            this.mList.addAll(0, list);
            notifyDataSetChanged();
        }
    }

    /**
     * 添加数据列表到列表尾部
     */
    public void addListAtEnd(List<T> list) {
        if (list != null && !list.isEmpty()) {
            this.mList.addAll(list);
            notifyItemRangeInserted(mList.size() - 1, list.size());
        }

    }

    /**
     * 添加数据列表到列表尾部
     */
    public void addListAtEndAndNotify(List<T> list) {
        if (list != null && !list.isEmpty()) {
            this.mList.addAll(list);
            notifyDataSetChanged();
        }
    }

    /**
     * 添加单个元素到列表头
     */
    public void addListBeanAtStart(T t) {
        if (t != null) {
            mList.add(0, t);
            notifyItemInserted(0);
        }

    }

    /**
     * 添加单个元素到列表尾
     */
    public void addListBeanAtEnd(T t) {
        if (t != null) {
            mList.add(t);
            notifyItemInserted(mList.size() - 1);
        }

    }

    /**
     * 替换RecyclerView数据
     */
    public void replaceList(List<T> list) {
        if (list != null){
            this.mList = list;
        } else {
            mList.clear();
        }

        notifyDataSetChanged();
    }

    /**
     * 替换RecyclerView中的某一个数据
     */
    public void replaceItem(T t, int position) {
        if (position >= 0 && position <= mList.size() && t != null) {
            this.mList.set(position, t);
            notifyItemChanged(position);
        }
    }

    /**
     * 删除RecyclerView所有数据
     */
    public void removeAll() {
        if (mList != null) {
            notifyItemRangeRemoved(0, mList.size());
            this.mList.clear();
        }
    }

    /**
     * 删除RecyclerView指定位置的数据
     */
    public void remove(T t) {
        if(mList != null) {
            this.mList.remove(t);
            notifyDataSetChanged();
        }
    }

    /**
     * 删除RecyclerView指定位置的数据
     */
    public void remove(int position) {
        if (position >= 0 && position <= mList.size() && mList != null) {
            this.mList.remove(position);
            notifyItemRemoved(position);
        }
    }

    /**
     * item点击事件抽象方法
     */
    public AdapterView.OnItemClickListener getOnItemClickListener() {
        return onItemClickListener;
    }

    public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    /**
     * item长按事件抽象方法
     */
    public AdapterView.OnItemLongClickListener getOnItemLongClickListener() {
        return onItemLongClickListener;
    }

    public void setOnItemLongClickListener(AdapterView.OnItemLongClickListener onItemLongClickListener) {
        this.onItemLongClickListener = onItemLongClickListener;
    }

    /**
     * 点击事件抽象方法
     */
    public void setOnHolderClick(ViewHolderClick<T> holderClick) {
        this.holderClick = holderClick;
    }

    public interface ViewHolderClick<T> {
        void onViewClick(View view, T t, int position);
    }
}

调用方法:

注意:DeviceBean是一个对象,你可以传任何对象或者String,int,long等,调用的时候只需要mAdapter.replaceList(List<DeviceBean>);即可。

/**
 * 类说明:我的设备
 * Author: gaobaiq
 * Date: 2016/8/12 10:27
 */
public class MyDeviceAdapter extends CommonRecyclerAdapter<DeviceBean> {

    public MyDeviceAdapter(Context context) {
        super(context);
    }

    @Override public int onCreateViewLayoutID(int viewType) {
        return R.layout.item_of_my_device;
    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, int position) {
        DeviceBean bean = mList.get(position);
        //TextView tvTitle = holder.get(R.id.tv_title);
        //tvTitle.setText(bean.getTitle());

        holder.setText(R.id.tv_title, bean.getTitle());
    }
}
时间: 2024-11-15 03:50:53

RecyclerAdapter基类的相关文章

当this指针成为指向之类的基类指针时,也能形成多态

this指针: 1)对象中没有函数,只有成员变量 2)对象调用函数,通过this指针告诉函数是哪个对象自己谁. 1 #include<iostream> 2 using namespace std; 3 class Shape 4 { 5 public: 6 //void cal_display(Shape* this) 7 void cal_display(){ 8 display(); 9 this->display(); 10 } 11 private: 12 virtual vo

基于MVC4+EasyUI的Web开发框架形成之旅--基类控制器CRUD的操作

在上一篇随笔中,我对Web开发框架的总体界面进行了介绍,其中并提到了我的<Web开发框架>的控制器的设计关系,Web开发框架沿用了我的<Winform开发框架>的很多架构设计思路和特点,对Controller进行了封装.使得控制器能够获得很好的继承关系,并能以更少的代码,更高效的开发效率,实现Web项目的开发工作,整个控制器的设计思路如下所示. 从上图的设计里面可以看到,我把主要能通过抽象封装的CRUD方法都放到了BusinessController<B, T>类里面,

C++中虚基类

摘自<C++程序设计> 如果一个派生类有多个直接基类,而这些直接基类又有一个共同的基类,则在最终的派生类中会保留该间接共同基类数据成员的多份同名成员. C++提供虚基类(virtual base class)的方法,使得在继承间接共同基类时只保留一份成员. 下面举例说明: 在如下的图中: Person类是Student和Teacher的基类,而Graduate类又继承自Student和Teacher类. 如果使用虚基类的话,Graduate将有两份age拷贝,两份gender拷贝,两份name

UI(UGUI)框架(二)-------------UIManager单例模式与开发BasePanel面板基类/UIManage统一管理UI面板的实例化/开发字典扩展类

UIManage单实例: 1 /// 单例模式的核心 2 /// 1,定义一个静态的对象 在外界访问 在内部构造 3 /// 2,构造方法私有化 4 5 private static UIManager _instance; 6 7 public static UIManager Instance 8 { 9 get 10 { 11 if (_instance == null) 12 { 13 _instance = new UIManager(); 14 } 15 return _instan

从设计基类及其派生类看继承关系

继承能够定义可重用.扩展或修改父类行为的子类.但基类的静态构造函数.实例构造函数和析构函数不能被派生类继承. 在下面实例中,定义一个基类Publication用于表示任何类型的出版物以及派生至Publication的其他类型Book类,由此也可以扩展为定义其他类型如:Magazine.Journal.Newspaper和Article. 在设计基类Publication时我们必须考虑到如下关系: 1.要在基类中添加哪些成员 2.基类是否用作派生类模板的抽象基类 3.类层次结构的扩展空间大小,要开

EF增删查改基类

/// <summary> /// EF DAL CURD基类 /// </summary> /// <typeparam name="T"></typeparam> public class BaseDAL<T> where T : class, new() { /// <summary> /// 上下文网关 /// </summary> protected SchoolEntities db = n

派生类和基类的转换

指针引用分四种情况: 1.直接用基类指针引用基类对象 2.直接用派生指针引用派生对象 3.由基类指针引用派生类对象,由于派生类也是基类对象(包含关系),所以这种引用是安全的.但是只能引用基类成员,若试图通过基类指针引用那些只在派生类中才有的成员,编译器会报告语法错误.(解决该问题的答案是虚函数和多态性) 4.用派生类指针引用基类对象,这种方式会导致编译器报错.必须先把派生类指针强制转换成基类指针. 如果基类和派生类都定义了同名函数,通过对象指针调用成员函数时,到底调用哪里的函数由指针的原始类型决

第六篇:为多态基类声明虚析构函数

前言 在很多类中,可以看到其析构函数都是声明为虚函数的. 那么,为何要将析构函数声明为虚函数?哪些情况要将析构函数声明为虚函数? 本文将为你解惑. 在使用 C++ 实现多态的时候,有一点一定要清楚:当派生类对象经由基类指针被删除,而此基类的析构函数没有被声明为虚函数的话,那么析构函数只会释放基类部分的成员而无视派生类成员. 如果不对这一点加以防范,那么很多时候,会带来内存泄露这样灾难性的后果. 问题描述 假设,有以下几个类,分别代表:钟,原子钟,水钟,腕表: 1 // 钟 2 class Tim

C#派生类中使用基类protected成员的方法

我们知道C#中通过继承可以使一个具有公共数据和方法的基类被广泛应用从而减少代码量,这样派生类会具有基类中所有成员(除构造器等),我们理所当然可以通过派生类实例来使用基类的成员.那么当基类成员被protected修饰时,我们应该怎么在派生类中使用基类成员呢,下面将介绍使用方法. 首先我们贴一段错误的使用代码: 1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Console.ReadLine(); 6 7 } 8 } 9 pub