RecyclerView并不像listView 那样有方法可以直接添加 footer或者header 所有我们只能通过另一种方式来添加了
下面看代码
public class HeaderAndFooterAdapter<T extends RecyclerView.Adapter> extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private final T mBase; private List<View> headers = new ArrayList<>(); private List<View> footers = new ArrayList<>(); private final int headerType = -1000; private final int footerType = -2000; public HeaderAndFooterAdapter(T base){ mBase = base; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if(isHeader(viewType)){ RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(headers.get(viewType - headerType)) { }; return viewHolder; }else if(isFooter(viewType)){ RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(footers.get(viewType - footerType)) { }; return viewHolder; }else { return mBase.onCreateViewHolder(parent, viewType); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (position < headers.size()) { } else if (position < headers.size() + mBase.getItemCount()) { mBase.onBindViewHolder(holder, position - headers.size()); } else { } } @Override public int getItemCount() { return headers.size() + footers.size() + mBase.getItemCount(); } private boolean isHeader(int viewType){ return viewType >= headerType && viewType < headerType + headers.size(); } private boolean isFooter(int viewType){ return viewType >= footerType && viewType < footerType + footers.size(); } @Override public int getItemViewType(int position) { if(position < headers.size()){ return headerType + position; }else if(position < headers.size() + mBase.getItemCount()){ return mBase.getItemViewType(position - headers.size()); }else { return footerType + position; } } public void addHeader(View view){ headers.add(view); }
}
上面 其实也就是 通过 判断 item的位置 例如getItemViewType方法中 如果 position < headers.size 证明他是 headerView
然后返回viewType 其他方法中就可以通过这个 getItemViewType 来进行处理了