Android 5.X new features for Recyclerview add Headerview and Footerview

Source: Internet
Author: User

In the previous section we talked about the new features of Android 5.X Recyclerview basic analysis and infinite reuse I believe you should also be familiar with the basic use of Recyclerview, this section we come to learn, Add Headerview and Footerview to Recyclerview.

For Recyclerview's head and bottom, the authorities did not provide us with a way to directly pass the Addheaderview ()/addfooterview () like a ListView, so we can only do it on our own, how to achieve it? As we all know, Recyclerview has encapsulated adapter and Viewholder for us, and in adapter we need to rewrite Oncreateviewholder (viewgroup parent, int viewtype) This method allows us to pass the Itemview layout file or custom view to the Viewholder to achieve itemview reuse and recycling. And what we're going to talk about today is that adding a head and a bottom is inextricably related to the method.

Let's take a closer look at Oncreateviewholder (viewgroup parent, int viewtype), which contains a viewtype in its arguments, which represents the type of itemview in each of the sub-lists, And this type can be defined by the Getitemviewtype () method encapsulated in the adapter. Therefore, we can follow these two methods to complete our study today.

First, we also need to add a Addheaderview method to the Baserecycleradapter to accept the Headerview passed in the activity, and add Headerview to the No. 0 itemview.

    private View mHeaderView;    publicvoidaddHeaderView(View headerView){        mHeaderView = headerView;        notifyItemInserted(0);    }

We then rewrite the Getitemviewtype () method in our custom baserecycleradapter and define two static variables to differentiate our ViewType type, as follows:

    0;    1;    @Override    public int getItemViewType(int position) {        return super.getItemViewType(position);    }

OK, now we can set the ViewType type for our itemview for the Getitemviewtype () method. We know that Getitemviewtype () returns the type 0 by default, so we overload the method, and when there is no mheaderview, we let it return to the Type_body type, and when there is Mheaderview, Because it was added to the No. 0 Itemview, we can make it return to Type_header type when position equals 0. The defined type will be used in Oncreateviewholder ().

So our Getitemviewtype method can be designed like this:

    @Override    public int getItemViewType(int position) {        if(mHeaderView == null)            return TYPE_BODY;        if0) {            return TYPE_HEADER;        }        return TYPE_BODY;    }

Now that we have a clear idea of the ViewType type of each itemview, we can make different judgments in the Oncreateviewholder () method based on the viewtype of Itemview, as follows:

    @Override    public BaseViewHolderHelper onCreateViewHolder(ViewGroup parent, int viewType) {        if(viewType == TYPE_HEADER && mHeaderView != null){            return new BaseViewHolderHelper(mHeaderView);        }        View view = LayoutInflater.from(parent.getContext()).inflate(mLayoutResId, parent, false);        return new BaseViewHolderHelper(view);    }

Code at a glance, is based on ViewType to determine whether it is type_header, if so, add a different layout or view, otherwise, load the normal layout, the other unchanged.

We can then bind to the current position position in the Onbindviewholder (baseviewholderhelper holder, int position) method to display the data.

  @Override  public void Onbindviewholder (baseviewholderhelper holder, int position) {if  (Geti        Temviewtype (position) = = Type_header) {return ;                }else  {if  (Mheaderview! = null) {            position--;            } holder.itemView.setTag (position);            Holder.itemView.setOnClickListener (this);            Holder.itemView.setOnLongClickListener (this);            T ItemData = mdatas.get (position);        Displaycontents (Holder,itemdata); }    }

Code explanation: If the current position position type is type_header, that is used to display Mheaderview, here we directly return to the layout of Mheaderview, do not do event processing; And Recyclerview is with Mheaderview head, so since it takes up No. 0 itemview, so our position is calculated from the first, so we have to get the current real position position, and through the position location to obtain the current real data, if not with Mheaderview head, you can directly according to position to obtain the display data, the other logic does not change.

Also note that when the Mheaderview is not empty, our data volume size also has a certain change, see:

    @Override    public int getItemCount() {        return1 : mDatas.size();    }

Ok, add two sentences to Recyceractivity's OnCreate method:

View headerView = LayoutInflater.from(this).inflate(R.layout.item_view1, null);mBaseRecyclerAdapter.addHeaderView(headerView);

Let's take a look at the running results

OK, the addition of Mheaderview has been completed. But there is a small problem, when you set the layout of Recyclerview to Gridlayoutmanager, such as: Mrecyclerview.setlayoutmanager (New Gridlayoutmanager (this,2)) ; This can happen:

This is also a good solution, in Gridlayoutmanager we can reset the number of columns displayed in Spansizelookup.

  @Override         public void Onattachedtorecyclerview (Recyclerview recyclerview) {Super.onattachedtorecyclerview (RecyclerView);        Recyclerview.layoutmanager manager = Recyclerview.getlayoutmanager (); if  (Manager instanceof Gridlayoutmanager)            {Final Gridlayoutmanager Gridlayoutmanager = ((Gridlayoutmanager) manager); Gridlayoutmanager.setspansizelookup (New Gridlayoutmanager.spansizelookup () {@                    Override  public int getspansize (int position) {//Is headerview for all columns, otherwise it only occupies its own column return  getitemviewtype (position) = = Type_header?                Gridlayoutmanager.getspancount (): 1 ;        }            }); }    }

The main thing is to re-set the Getspansize method according to our needs is OK. Take a look.

Well, Mheaderview has basically done, now look at how to add footerview, in fact, the principle is the same, but also according to Getitemviewtype () return ViewType type to load different layouts.

First we need to define an inner class Footerviewholder to inherit our Baseviewholderhelper, which is primarily used to bind Footerview layout files:

    class FooterViewHolder extends BaseViewHolderHelper{        private TextView footView;        public FooterViewHolder(View itemView) {            super(itemView);            footView = (TextView) itemView.findViewById(R.id.tv_addFooter);        }    }

It then obtains the position of the last Itemview in Getitemviewtype and returns the Type_footer type:

@Override    private View mFooterView;    2;    ......    public int getItemViewType(int position) {        if1 == getItemCount()){            return TYPE_FOOTER;        }        if(mHeaderView == null)            return TYPE_BODY;        if0) {            return TYPE_HEADER;        }        return TYPE_BODY;    }

In addition, in the GetItemCount () method We need to add 1 on the original basis because we added a footerview.

    @Override    public int getItemCount() {        return21;    }

Load the different layout files according to the type again in the Oncreateviewholder method:

@Override    public BaseViewHolderHelper onCreateViewHolder(ViewGroup parent, int viewType) {        ...        if(viewType == TYPE_FOOTER){            mFooterView = LayoutInflater.from(mContext).inflate(R.layout.custom_footerview, parent,false);            return new FooterViewHolder(mFooterView);        }        View view = LayoutInflater.from(parent.getContext()).inflate(mLayoutResId, parent, false);        return new BaseViewHolderHelper(view);    }

Finally, let's show our data in the Onbindviewholder method.

    @Override    public void onBindViewHolder(BaseViewHolderHelper holder, int position) {        if(getItemViewType(position) == TYPE_HEADER){            return;        }elseif(getItemViewType(position) == TYPE_FOOTER){            FooterViewHolder footViewHolder=(FooterViewHolder)holder;            footViewHolder.footView.setText("上拉加载更多...");        else{            ...        }    }

OK, finish, let's see the results.

In summary, when adding Headerview and Footerview to Recyclerview, as long as the method of good getitemviewtype is used, the corresponding ViewType is returned, and loading different layouts based on the ViewType type in the Oncreateviewholder method is exactly what we need to achieve. That's the simple thing to say. Well, let's talk about it today, and wish you all a pleasant study.

For more information please pay attention to the platform, blog updates will be timely notification. Love to learn love technology.

Android 5.X new features for Recyclerview add Headerview and Footerview

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.