RecyclerView通用的适配器

列表的展现形式在项目中很常见,每次用到recyclerView都要重新写一个adapter特别繁琐,结合网上的资料自己写了一个简单的通用适配器,方便之后项目中使用

第一步,定义ViewHolder

public class ViewHolder extends RecyclerView.ViewHolder {

    private SparseArray mViews;
    private View mConvertView;
    private Context mContext;

    public ViewHolder(Context context, View itemView, ViewGroup parent) {
        super(itemView);
        mContext = context;
        mConvertView = itemView;
        mViews = new SparseArray();
    }

    public static ViewHolder get(Context context, ViewGroup parent, int layoutId) {

        View itemView = LayoutInflater.from(context).inflate(layoutId, parent,
                false);
        ViewHolder holder = new ViewHolder(context, itemView, parent);
        return holder;
    }


    public  T getView(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }


    public ViewHolder setText(int viewId, String text)
    {
        TextView tv = getView(viewId);
        tv.setText(text);
        return this;
    }

    public ViewHolder setOnClickListener(int viewId, View.OnClickListener listener) {
        View view = getView(viewId);
        view.setOnClickListener(listener);
        return this;
    }

}

第二步,定义通用类型的adapter

public abstract class CommonAdapter extends RecyclerView.Adapter {

    protected Context mContext;
    protected int mLayoutId;
    protected List mDatas;
    protected LayoutInflater mInflater;


    public CommonAdapter(Context context, int layoutId, List datas) {
        mContext = context;
        mInflater = LayoutInflater.from(context);
        mLayoutId = layoutId;
        mDatas = datas;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ViewHolder viewHolder = ViewHolder.get(mContext, parent, mLayoutId);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        convert(holder, mDatas.get(position));
    }

    public abstract void convert(ViewHolder holder, T t);


    @Override
    public int getItemCount() {
        return mDatas.size();
    }
}

第三步,传值使用

        CommonAdapter adapter1 = new CommonAdapter(this, R.layout.adapter_test, list) {
            @Override
            public void convert(ViewHolder holder, String s) {
                holder.setText(R.id.tv_value, s);
                holder.setOnClickListener(R.id.tv_value, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(SecondActivity.this, "this" + s, Toast.LENGTH_LONG).show();
                    }
                });
            }
        };
        recyclerView.setAdapter(adapter1);

 

你可能感兴趣的:(RecyclerView通用的适配器)