欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RecycleView万能适配器

程序员文章站 2024-03-17 09:17:58
...

1.万能适配器:

public abstract class YzpRecycleViewAdapter<T> extends RecyclerView.Adapter<YzpRecycleViewAdapter.VH> {

    private List<T> mData;

    public YzpRecycleViewAdapter(List<T> mData) {
        this.mData = mData;
    }

    public abstract int getLayoutId(int viewType);

    @Override
    public VH onCreateViewHolder(ViewGroup parent, int viewType) {
        return VH.get(parent, getLayoutId(viewType));
    }

    @Override
    public void onBindViewHolder(VH holder, int position) {
        convert(holder, mData.get(position), position);
    }

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

    public abstract void convert(VH holder, T data, int position);

    public static class VH extends RecyclerView.ViewHolder {
        private SparseArray<View> mViews;
        private View mConvertView;

        private VH(View v) {
            super(v);
            mConvertView = v;
            mViews = new SparseArray<>();
        }

        public static VH get(ViewGroup parent, int layoutId) {
            View convertView = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
            return new VH(convertView);
        }

        public <T extends View> T getView(int id) {
            View v = mViews.get(id);
            if (v == null) {
                v = mConvertView.findViewById(id);
                mViews.put(id, v);
            }
            return (T) v;
        }

        public void setText(int id, String value) {
            TextView view = getView(id);
            view.setText(value);
        }
    }
}

2.使用万能适配器

private List<Order> list;
private YzpRecycleViewAdapter<Order> adapter;

adapter = new YzpRecycleViewAdapter<Order>(list) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.order_item;
            }

            @Override
            public void convert(YzpRecycleViewAdapter.VH holder, Order order, int position) {
                holder.setText(R.id.tv_name, order.getName());
                holder.getView(R.id.tv_name).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(MainActivity.this, order.getName(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };
        recycleView.setAdapter(adapter);
        DividerItemDecoration decoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        decoration.setDrawable(getResources().getDrawable(R.drawable.divider, null));
        recycleView.addItemDecoration(decoration);

可参见:Android 控件 RecyclerView

相关标签: android 列表