How to add headers and footer_android for Recyclerview

Source: Internet
Author: User
Tags inheritance xmlns

In the past two days, in the project, abandoned the ListView, want to try Recyclerview, in the process, encountered some problems, such as: How to add headers and footer for Recyclerview? How do I add a split line for Recyclerview? How do I add a drop-down refresh and a pull load for Recyclerview? In the next period of time, I will focus on these several issues, by writing a book of the way one by one to tell, today brings you the first solution to the problem, how to add headers and footer for Recyclerview? Before that, I would like to share my knowledge of Recyclerview:

One. The Recyclerview in my eyes
Over the past year or two, Recyclerview has attracted more and more attention from our Android developers, and even a lot of people say: ListView, the GridView has gradually been replaced by Recyclerview, The main reason is the flexibility of recyclerview, as well as the improvement of performance. Then perhaps a lot of people will ask: Recyclerview and ListView, what is the GridView relationship? A set of screenshots from the official Android document tells you:

Family spectrum of ListView (Inheritance structure)

Family spectrum of Recyclerview (inheritance structure)

Through the above two diagrams can be found, ListView inherited from: Abslistview. (Girdview also), Recyclerview directly inherited ViewGroup, finally came to the conclusion: Recyclerview is ListView Grandpa Generation, that is, Recyclerview is the listview of the two Ye, So from the packaging level to get why Recyclerview performance than listview better reason, because the higher the level of encapsulation, query execution speed is relatively slow, of course, there is also a reason, Recyclerview in the adapter of the band joined the holder, Forced developers to use, in ListView, many people do not understand the use of holder, which also led to the use of ListView performance is poor. This is also a major reason for recyclerview performance improvement, of course, the higher the packaging layer, the more flexible, relatively difficult to use, many methods are through their own encapsulation, such as ListView in the Addheaderview (view view), Addfooterview (view view) to add your own header and footer, but not in Recyclerview, I will explain in detail below:

Two. Add headers and footer for Recyclerview

1. Know Header and Footer
let you know the header and footer by using two diagrams of the following Jane book

Diagram with header


A picture with footer

With the above two graphs, you can see that headers and footer are often accessible in many cases, such as headers are usually used for advertising, and footer more to show the drop load as a visual component to enhance the user experience.

2. Using code to resolve how to add headers and footer
recyclerview for Recyclerview is similar to the use of ListView. Nothing more than that three steps:
First, initialize Recyclerview;
Second, initialize the data and load the data through adapter into view;
third, by Setadapter method, Bind the adapter to the Recyclerview.
Directly below the code: explains the Add headers and footer by means of a code comment:
(1) Master layout layout_main.xml: Just added a recyclerview.

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayoutxmlns:android= 
"http://schemas.android.com/apk" /res/android "
 xmlns:tools=" Http://schemas.android.com/tools " 
 android:layout_width=" Match_parent 
 " android:layout_height= "Match_parent" 
 android:paddingbottom= "@dimen/activity_vertical_margin" 
 android: paddingleft= "@dimen/activity_horizontal_margin" 
 android:paddingright= "@dimen/activity_horizontal_margin" 
 android:paddingtop= "@dimen/activity_vertical_margin" 
 tools:context= " Com.study.wnw.recyclerviewheaderfooter.MainActivity "> 
 <android.support.v7.widget.recyclerview 
  Android:id= "@+id/recyclerview" 
  android:layout_width= "match_parent" 
  android:layout_height= "Match_" Parent "/> 
</RelativeLayout>

(2) The Item layout of ListView in Recyclerview List_item.xml: Just added a TextView

<?xml version= "1.0" encoding= "Utf-8" ><linearlayout 
  xmlns:android= "http://schemas.android.com/apk/" Res/android " 
  android:orientation=" vertical " 
  android:layout_width=" match_parent " 
  android:layout_" height= "50DP" > 
  <textview 
   android:id= "@+id/item" 
  android:layout_width= "Match_parent" 
  android:layout_height= "Match_parent" 
  android:textsize= "20sp" 
  android:textcolor= "@color/coloraccent" 
  android:gravity= "center" 
  android:background= "#08e630"/> 
</LinearLayout>

(3) Headerview and Footerview layout files, also a textview, where only the Headerview layout is posted, footerview layout files are the same as Footerview:

Headerview layout file: header.xml:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android "  
 android:orientation=" vertical " 
 android:layout_width=" match_parent " 
 android:layout_" height= "100DP" > 
 <textview  
  android:id= "@+id/header" 
  android:layout_width= "Match_parent" 
  android:layout_height= "Match_parent" 
  android:text= "I am Header" 
  android:textsize= "30sp" 
  android: Textcolor= "#fde70b0b" 
  android:background= "#f9777979" 
  android:gravity= "center"/> 
</ Linearlayout>

All right, here we go. We're done here, so let's look directly at the contents of the mainactivity:

(4) The contents of the Mainactivity.java are:

Package com.study.wnw.recyclerviewheaderfooter; 
Import Android.app.activity;import Android.os.Bundle; 
Import Android.support.v7.widget.LinearLayoutManager; 
Import Android.support.v7.widget.RecyclerView; 
Import Android.view.LayoutInflater; 
Import Android.view.View; 

Import Java.util.arraylist;import java.util.List; 
 public class Mainactivity extends activity {private Recyclerview Mrecyclerview; 
 Private Myadapter Mmyadapter; 

 Private list<string> mlist; 
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 

  Setcontentview (R.layout.activity_main); 
  Recyclerview Trilogy +layoutmanager Mrecyclerview = (recyclerview) Findviewbyid (R.id.recyclerview); 
  Linearlayoutmanager Linearlayoutmanager = new Linearlayoutmanager (this); 
  Mrecyclerview.setlayoutmanager (Linearlayoutmanager); 
  InitData (); 
  Mmyadapter = new Myadapter (mlist); 

 Mrecyclerview.setadapter (Mmyadapter); Add Headerview and Footerview s to RecyclerviewEtheaderview (Mrecyclerview); 
 Setfooterview (Mrecyclerview); 
 }//Initialize data for each item in Recyclerview private void InitData () {mlist = new arraylist<string> (); 
 for (int i = 0; i < i++) {Mlist.add ("item" + i);  } private void Setheaderview (Recyclerview view) {View Header = Layoutinflater.from (this). Inflate (R.layout.header, 
  View, false); 
 Mmyadapter.setheaderview (header); private void Setfooterview (Recyclerview view) {View footer = Layoutinflater.from (this). Inflate (R.layout.footer, Vie  
 W, false); 
 Mmyadapter.setfooterview (footer);

 } 
}

From the above code, we can see that we do two things in mainactivity, one is to initialize Recyclerview-related view, Adapter, data, and the other is through our custom Adapter Setheaderview ( and Setfooterview () method to add Headerview and Footerview to Recyclerview, here we can't wait to know what's in the Myadapter, directly on the code

(5) Myadapter.java code

Package com.study.wnw.recyclerviewheaderfooter;
Import Android.support.v7.widget.RecyclerView;
Import Android.view.layoutinflater;import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.TextView;
Import java.util.List; /** * Created by WNW on 16-5-20. */public class Myadapter extendsrecyclerview.adapter<recyclerview.viewholder> {public static final int Type_head ER = 0; Description is the public static final int type_footer = 1 with header; Description is the public static final int type_normal = 2 with footer;
 Description is not with header and footer//get from the activity passed over the data collection of each item private list<string> Mdatas; 
 Headerview, Footerview private View Mheaderview; 

 Private View Mfooterview; 
 Constructor public Myadapter (list<string> list) {this.mdatas = list; 
 The Get and set functions for//headerview and Footerview are public View Getheaderview () {return mheaderview; 
 public void Setheaderview (View headerview) {mheaderview = Headerview; 
 notifyiteminserted (0); } public View GetfootervIew () {return mfooterview; 
 public void Setfooterview (View footerview) {mfooterview = Footerview; 
 Notifyiteminserted (GetItemCount ()-1); /** Rewrite This method, it is important to join header and footer key, we by judging the type of item, thus binding different view * * * * * * @Override public int getitemviewtype (int positio 
 N) {if (Mheaderview = = NULL && Mfooterview = null) {return type_normal; 
 } if (position = 0) {//The first item should load HEADER return type_header; 
 } if (position = = GetItemCount ()-1) {//Last, should load FOOTER return type_footer; 
 return type_normal; //CREATE VIEW, if it is Headerview or Footerview, return directly to the holder @Override public Recyclerview.viewholder Oncreateviewholder (Vie Wgroup parent, int viewtype) {if (Mheaderview!= null && ViewType = = Type_header) {return new Listholder (MH 
 Eaderview); 
 } if (Mfooterview!= null && ViewType = = type_footer) {return new Listholder (Mfooterview); View layout = Layoutinflater.from (Parent.getcontext ()). Inflate (R.layout.list_item, parent, false); 
 return new Listholder (layout); }//Bind view, which is bound by the type of the returned position, Headerview and Footerview, @Override public void Onbindviewholder are bound differently (recy Clerview.viewholder holder, int position) {if (Getitemviewtype (position) = = Type_normal) {if (Holder instanceof Listh Older) {//the time to load data here is to note that starting from position-1, because Position==0 has been occupied by the header ((listholder) holder). Tv.settext (Mdatas.get (posit  
  ion-1));  
  Return 
 } return;  
 }else if (getitemviewtype (position) = = Type_header) {return; 
  }else{return; 
 The layout class Listholder extends recyclerview.viewholder{TextView TV for each item in the ListView is loaded in this area;  
  Public Listholder (View Itemview) {super (Itemview);  
  If it is Headerview or footerview, return directly if (Itemview = = Mheaderview) {returns;  
  } if (Itemview = = Mfooterview) {return; 
  TV = (TextView) Itemview.findviewbyid (R.id.item); 
}//Return the number of items in view, this time, the total number should be the number of items in ListView plus Headerview and Footerview @Override public int GetItemCount () {if (Mheaderview = = NULL && Mfooterview = null) {return mdatas.size (); 
 }else if (Mheaderview = = null && mfooterview!= null) {return mdatas.size () + 1; 
 }else if (mheaderview!= null && Mfooterview = null) {return mdatas.size () + 1; 
 }else {return mdatas.size () + 2;

 } 
 }
}

From the Myadapter class above, there are Setheaderview () and Setfooterview () two methods, which we pass from the activity to Headerview and Footerview. In the Oncreateviewholder () method in adapter, use Getitemviewtype () to return the type of item (is your item header?). Or the footer family? Or the ListView family? Depending on the type, we create a view of the different item. The idea is like this, more details please see code comments, the following is a screenshot of the operation (because do not know what the Linux under the Good GIF generation tool, can only intercept static diagram, you know, you can recommend to me, thank you great God):

Header

Footer

Finally finished, need to slowly digest and absorb, this is just a way to achieve headerview and Footerview, we see from here, Headerview and Footerview is directly from the activity passed adapter, We can also like ListView, we only pass Headerview and Footerview data over adapter, then create different adapter and Headerholder inside Footerholder, According to the type of return item, load different holder can, concrete realization I don't say more, we can go to realize. Through the screenshot, you will find that in the Recyclerview, there is no split line between each item, and there is no Recyclerview setdivider () Such a way to set the split line, because Recyclerview flexible ah, so it is also to customize, In fact, it is very simple, the next article I will bring how to add a split line for Recyclerview, this is the end of this, there are deficiencies, I hope everyone a lot of advice, thank you.
Recyclerview added separator line has been implemented, Recyclerview series (2): For Recyclerview Add separator line, thank you for your support.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.