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);
上一篇: fresco图片加载框架
下一篇: 零碎知识点整理