Android 簡捷地為RecyclerView新增HeadView和FootView
阿新 • • 發佈:2019-01-22
之前自己嘗試用ViewType的思路去實現為RecyclerView新增HeadView和FootView,總感覺自己寫的程式碼太囉嗦了,向兩位大神學習了一下他們的編碼思路寫了個簡單了些的,分享給大家。
廢話不多說,上圖上程式碼。
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> { private View headView; private View footView; public static final int HEAD = 1; public static final int NORMAL = 2; public static final int FOOT = 3; private List<String> datas; public RecyclerAdapter(List<String> datas) { this.datas = datas; } public void addHeadView(View headView) { this.headView = headView; } public void addFootView(View footView) { this.footView = footView; } public int getHeadViewCount() { return headView == null ? 0 : 1; } public int getFootViewCount() { return footView == null ? 0 : 1; } @Override public int getItemCount() { return datas.size() + getHeadViewCount() + getFootViewCount(); } @Override public int getItemViewType(int position) { if (position < getHeadViewCount()) return HEAD; if (position >= datas.size() + getHeadViewCount()) return FOOT; return NORMAL; } @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { if (viewType == HEAD) return new ViewHolder(headView); if (viewType == FOOT) return new ViewHolder(footView); View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_recycleritem, null); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { if (getItemViewType(position) == HEAD) return; if (getItemViewType(position) == FOOT) return; holder.tvItem.setText(datas.get(position-getHeadViewCount())); } class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.tv_item) TextView tvItem; public ViewHolder(View itemView) { super(itemView); if (itemView == headView) return; if (itemView == footView) return; ButterKnife.bind(this, itemView); } } }