Is there an addHeaderView equivalent for RecyclerView?

后端 未结 19 1615
独厮守ぢ
独厮守ぢ 2020-11-21 23:35

I\'m looking for an equivalent to addHeaderView for a recycler view. Basically I want to have an image with 2 buttons be added as a header to the listview. Is there a differ

19条回答
  •  醉话见心
    2020-11-22 00:20

    There isn't an easy way like listview.addHeaderView() but you can achieve this by adding a type to your adapter for header.

    Here is an example

    public class HeaderAdapter extends RecyclerView.Adapter {
        private static final int TYPE_HEADER = 0;
        private static final int TYPE_ITEM = 1;
        String[] data;
    
        public HeaderAdapter(String[] data) {
            this.data = data;
        }
    
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_ITEM) {
                //inflate your layout and pass it to view holder
                return new VHItem(null);
            } else if (viewType == TYPE_HEADER) {
                //inflate your layout and pass it to view holder
                return new VHHeader(null);
            }
    
            throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
        }
    
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof VHItem) {
                String dataItem = getItem(position);
                //cast holder to VHItem and set data
            } else if (holder instanceof VHHeader) {
                //cast holder to VHHeader and set data for header.
            }
        }
    
        @Override
        public int getItemCount() {
            return data.length + 1;
        }
    
        @Override
        public int getItemViewType(int position) {
            if (isPositionHeader(position))
                return TYPE_HEADER;
    
            return TYPE_ITEM;
        }
    
        private boolean isPositionHeader(int position) {
            return position == 0;
        }
    
        private String getItem(int position) {
            return data[position - 1];
        }
    
        class VHItem extends RecyclerView.ViewHolder {
            TextView title;
    
            public VHItem(View itemView) {
                super(itemView);
            }
        }
    
        class VHHeader extends RecyclerView.ViewHolder {
            Button button;
    
            public VHHeader(View itemView) {
                super(itemView);
            }
        }
    }
    

    link to gist -> here

提交回复
热议问题