美文网首页进阶Android知识Android拾遗
为RecyclerView添加header和footer

为RecyclerView添加header和footer

作者: JC_Hou | 来源:发表于2016-11-24 13:58 被阅读923次

    RecyclerView和各种LayoutManager都没有直接的方法添加header和footer,因此我们就需要思考如何为RecyclerView添加header和footer了。
    这里我的解决方案和网上你能搜到的大多数方案一样,是通过控制Adapter的itemType来设置的,思路就是根据不同的itemType去加载不同的布局

    先po上完整代码

    public class PubuAdapter extends RecyclerView.Adapter<PubuAdapter.PubuHolder> {
        public static final int TYPE_HEADER = 0; 
        public static final int TYPE_FOOTER = 1;  
        public static final int TYPE_NORMAL = 2;  
    
        private List<DataBean> mList;
    
        //HeaderView, FooterView
        private View mHeaderView;
        private View mFooterView;
    
        public PubuAdapter(List<DataBean> mList) {
            this.mList=mList;
        }
    
        public View getmHeaderView() {
            return mHeaderView;
        }
    
        public void setmHeaderView(View mHeaderView) {
            this.mHeaderView = mHeaderView;
            //shouweicharu
            notifyItemInserted(0);
        }
    
        public View getmFooterView() {
            return mFooterView;
        }
    
        public void setmFooterView(View mFooterView) {
            this.mFooterView = mFooterView;
            if (mHeaderView==null){
                notifyItemInserted(mList.size());
            }else {
                notifyItemInserted(mList.size()+1);
            }
        }
    
        @Override
        public int getItemViewType(int position) {
            if (mHeaderView==null){
                if (mFooterView==null){
                    return TYPE_NORMAL;
                }else{
                    if (position==mList.size()){
                        return TYPE_FOOTER;
                    }else{
                        return TYPE_NORMAL;
                    }
                }
            }else {
                if (position==0){
                    return TYPE_HEADER;
                }else{
                    if (mFooterView==null){
                        return TYPE_NORMAL;
                    }else{
                        if (position!=mList.size()+1){
                            return TYPE_NORMAL;
                        }else{
                            return TYPE_FOOTER;
                        }
                    }
                }
            }
        }
    
        @Override
        public PubuHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (mHeaderView!=null&&viewType==TYPE_HEADER){
                return new PubuHolder(mHeaderView);
            }else if (mFooterView!=null&&viewType==TYPE_FOOTER){
                return new PubuHolder(mFooterView);
            }
            return new PubuHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_item,parent,false));
        }
    
        @Override
        public void onBindViewHolder(PubuHolder holder, int position) {
            if (getItemViewType(position)==TYPE_HEADER||getItemViewType(position)==TYPE_FOOTER){
                return;
            }else if (getItemViewType(position)==TYPE_NORMAL){
                holder.imageView.setImageResource(mList.get(position-1).getImage());
                holder.textView.setText(mList.get(position-1).getText());
                //如果设置了回调,则设置点击事件
                final int realPosition = getRealPosition(holder);
                if(mOnItemClickListener!=null){
                    holder.imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
    //                        int pos=holder.getLayoutPosition();//布局真正的position,recyclerView进行添加,移除item时,会导致position位置变化
                            mOnItemClickListener.onItemClick(v,realPosition);
                        }
                    });
                    holder.imageView.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
    //                        int pos=holder.getLayoutPosition();//布局真正的position,recyclerView进行添加,移除item时,会导致position位置变化
                            mOnItemClickListener.onItemLongClick(v,realPosition);
                            return false;
                        }
                    });
                }
            }
        }
    
    //重写此方法,判断recyclerview的layoutmanager为GridLayoutManager的时候,是header和footer独占一行,而不是一个item
        @Override
        public void onAttachedToRecyclerView(final RecyclerView recyclerView) {
            super.onAttachedToRecyclerView(recyclerView);
            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
            if (layoutManager instanceof GridLayoutManager){
                final GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
                gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        return getItemViewType(position)==TYPE_HEADER||getItemViewType(position)==TYPE_FOOTER?gridLayoutManager.getSpanCount():1;
                    }
                });
            }
        }
    
    //重写此方法,判断recyclerview的layoutmanager为StaggeredGridLayoutManager的时候,是header和footer独占一行,而不是一个item
        @Override
        public void onViewAttachedToWindow(PubuHolder holder) {
            super.onViewAttachedToWindow(holder);
            ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
            if (layoutParams!=null&&layoutParams instanceof StaggeredGridLayoutManager.LayoutParams){
                StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) layoutParams;
                params.setFullSpan(getItemViewType(holder.getLayoutPosition())==TYPE_HEADER||getItemViewType(holder.getLayoutPosition())==TYPE_FOOTER);
            }
        }
    
    //获取item的真实位置
        private int getRealPosition(RecyclerView.ViewHolder viewHolder){
            int layoutPosition = viewHolder.getLayoutPosition();
            return mHeaderView==null?layoutPosition:layoutPosition-1;
        }
    
        @Override
        public int getItemCount() {
            if (mHeaderView==null){
                if (mFooterView==null){
                    return mList.size();
                }else {
                    return mList.size()+1;
                }
            }else{
                if (mFooterView==null){
                    return mList.size()+1;
                }else {
                    return mList.size()+2;
                }
            }
        }
    
        class PubuHolder extends RecyclerView.ViewHolder{
            ImageView imageView;
            TextView textView;
    
            public PubuHolder(View itemView) {
                super(itemView);
                if (itemView==mHeaderView)return;
                imageView= (ImageView) itemView.findViewById(R.id.pubu_img);
                textView= (TextView) itemView.findViewById(R.id.pubu_txt);
            }
        }
    
        interface onItemClickListener{
            void onItemClick(View view, int position);
            void onItemLongClick(View view, int position);
        }
    
        private onItemClickListener mOnItemClickListener;
    
        public void setOnItemClickListener(onItemClickListener mOnItemClickListener) {
            this.mOnItemClickListener = mOnItemClickListener;
        }
    }```
    
    >这里我们重写了getItemViewType方法,并根据位置来返回不同的type,这个type是我们预先商定好的常量,接在onCreateViewHolder方法中来判断itemType,如果是header,则返回我们设置的headerView,如果是footer,则返回我们设置的footerView,否则正常加载item布局
    
    Activity中的使用
    
        mRecycleView= (RecyclerView) findViewById(R.id.recycle_view);
        adapter=new PubuAdapter(mList);
        adapter.setOnItemClickListener(new PubuAdapter.onItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(MainActivity.this,(position+1)+"click", Toast.LENGTH_SHORT).show();
            }
    
            @Override
            public void onItemLongClick(View view, int position) {
                Toast.makeText(MainActivity.this,(position+1)+"long click", Toast.LENGTH_SHORT).show();
                adapter.removeData(position);
            }
        });
        //先设置layoutmanager,再添加headre、footer
        mRecycleView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false));
        adapter.setmHeaderView(LayoutInflater.from(this).inflate(R.layout.header,mRecycleView,false));
        View footer = LayoutInflater.from(this).inflate(R.layout.footer, mRecycleView, false);
        adapter.setmFooterView(footer);
        mRecycleView.setAdapter(adapter);```
    

    当使用GridLayoutManager和StaggeredGridLayoutManager的时候会出现header和footer占一个item而不是一行的问题,我们需要重写Adapter里面的两个方法来处理这个问题

    //重写此方法,判断recyclerview的layoutmanager为GridLayoutManager的时候,是header和footer独占一行,而不是一个item
        @Override
        public void onAttachedToRecyclerView(final RecyclerView recyclerView) {
            super.onAttachedToRecyclerView(recyclerView);
            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
            if (layoutManager instanceof GridLayoutManager){
                final GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
                gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        return getItemViewType(position)==TYPE_HEADER||getItemViewType(position)==TYPE_FOOTER?gridLayoutManager.getSpanCount():1;
                    }
                });
            }
        }
    
    //重写此方法,判断recyclerview的layoutmanager为StaggeredGridLayoutManager的时候,是header和footer独占一行,而不是一个item
        @Override
        public void onViewAttachedToWindow(PubuHolder holder) {
            super.onViewAttachedToWindow(holder);
            ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
            if (layoutParams!=null&&layoutParams instanceof StaggeredGridLayoutManager.LayoutParams){
                StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) layoutParams;
                params.setFullSpan(getItemViewType(holder.getLayoutPosition())==TYPE_HEADER||getItemViewType(holder.getLayoutPosition())==TYPE_FOOTER);
            }
        }```
    
    效果如下
    
    
    ![StaggeredGridLayoutManager.png](http:https://img.haomeiwen.com/i1814117/5299fd2cd3850918.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    
    
    ![GridLayoutManager.png](https://img.haomeiwen.com/i1814117/2e2d45588ec68d4b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    相关文章

      网友评论

      • 899e2d74bdeb:@Override
        public void onBindViewHolder(PubuHolder holder, int position) {
        if (getItemViewType(position)==TYPE_HEADER||getItemViewType(position)==TYPE_FOOTER){
        return;
        }else if (getItemViewType(position)==TYPE_NORMAL){
        holder.imageView.setImageResource(mList.get(position-1).getImage());
        holder.textView.setText(mList.get(position-1).getText());
        //如果设置了回调,则设置点击事件
        final int realPosition = getRealPosition(holder);
        if(mOnItemClickListener!=null){
        holder.imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        // int pos=holder.getLayoutPosition();//布局真正的position,recyclerView进行添加,移除item时,会导致position位置变化
        mOnItemClickListener.onItemClick(v,realPosition);
        }
        });
        holder.imageView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
        // int pos=holder.getLayoutPosition();//布局真正的position,recyclerView进行添加,移除item时,会导致position位置变化
        mOnItemClickListener.onItemLongClick(v,realPosition);
        return false;
        }
        });
        }
        }
        }
        这里还需要判断一下header存不存在,mList.get(position-1)才要减一
        JC_Hou:@哎疯 final int realPosition = getRealPosition(holder);
        private int getRealPosition(RecyclerView.ViewHolder viewHolder) {
        int layoutPosition = viewHolder.getLayoutPosition();
        return mHeaderView == null ? layoutPosition : layoutPosition - 1;
        }
        已经获取了真实position,可以直接使用,可以试一下

      本文标题:为RecyclerView添加header和footer

      本文链接:https://www.haomeiwen.com/subject/ltmbpttx.html