BaseAdapter

public abstract class BaseAdapter extends RecyclerView.Adapter{

    protected static final String TAG = BaseAdapter.class.getSimpleName();
    protected final Context context;
    public  int layoutResId;
    protected List datas;
    private List Livelist=new ArrayList<>();//sq:在Adapter下(就是添加一个标记集合,当是否点击,如果是就添加到这个集合中,否就移除,再判断一次当前是否在这个集合中,是就显示点击的状态,否就显示未点击状态)


    public OnItemClickListener mOnItemClickListener = null;

    public  interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }


    public BaseAdapter(Context context) {
        this(context, null);
    }

    public BaseAdapter(Context context,List datas) {
        this.datas = datas == null ? new ArrayList() : datas;
        this.context = context;
    }

    public void getLayout(int layoutResId){
        this.layoutResId=layoutResId;
    }

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup viewGroup,  int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(layoutResId, viewGroup, false);
        BaseViewHolder vh = new BaseViewHolder(view,mOnItemClickListener);
        return vh;
    }


    @Override
    public void onBindViewHolder(BaseViewHolder viewHoder,  int position) {
        T item = getItem(position);
        convert((H)viewHoder, item,position);
    }



    @Override
    public int getItemCount() {
        if(datas==null || datas.size()<=0)
            return 0;
        return datas.size();
    }


    public T getItem(int position) {
        if (position >= datas.size()) return null;
        return datas.get(position);
    }


    public void clear(){
        int itemCount = datas.size();
        datas.clear();
        this.notifyItemRangeRemoved(0,itemCount);
    }

    public List getDatas(){
        return  datas;
    }



    public void addData(List datas){

        addData(0,datas);
    }

    public void addData(int position,List datas){
        if(datas !=null && datas.size()>0) {
            this.datas.addAll(datas);
            this.notifyItemRangeChanged(position, datas.size());
        }
    }

    /**
     * Implement this method and use the helper to adapt the view to the given item.
     * @param viewHoder A fully initialized helper.
     * @param item   The item that needs to be displayed.
     * @param position
     */
    protected abstract void convert(H viewHoder, T item, int position);



}

你可能感兴趣的:(BaseAdapter)