自定义Adapter实现无限存余
继承无限循环adapter 重写实现有限adapter
背景
问题
- 当前存在的adapter为无限循环式 而当前需要显示的仅仅只是其中一部分数据信息 不想直接复制原先ViewHoloder以及onBindView内的数据
思路
- 重写getItemCount()以及onBindViewHolder方法
- 原先ViewHolder类中通过泛型获取控件ID以及通过ID设置文字以及图片等功能
实现
继承原适配器 重写方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class MLiveAdapter extends LiveAdapter { private List<live> liveList;
@Override public void onBindViewHolder(ViewHolder holder, int position) { live = liveList.get(position); holder.setImageRes(R.id.iv_live_icon, live.getImageId()); //省略... holder.setText(R.id.tv_live_trade_name, live.getTradeName()); holder.getView(R.id.l1_live_bg).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //省略... } }); super.onBindViewHolder(holder, position); }
public MLiveAdapter(List<live> liveList) { super(liveList); this.liveList = liveList; }
@Override public int getItemCount() { return liveList.size(); } }
|
获取ID 设置文字以及图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| protected static class ViewHolder extends RecyclerView.ViewHolder { ImageView image; TextView TradeName; LinearLayout liBg; View mConvertView; //省略... SparseArray<View> mViews;
public ViewHolder(View view) { super(view); //省略... image = view.findViewById(R.id.iv_live_icon); TradeName = view.findViewById(R.id.tv_live_trade_name); liBg = view.findViewById(R.id.l1_live_bg); mViews = new SparseArray<View>(); mConvertView=view; }
public <T extends View> 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 setImageRes(int viewID, int resId) { ImageView iv = getView(viewID); iv.setImageResource(resId); return this; } }
|
最后