Android recyclerview sticky headers

Sticky Header For RecyclerView

Jul 12, 2018 · 4 min read

A lot of us remember days that we were using listView to show a list. Those days there were a lot of libraries that could help us to create listView with sticky header, The headers stick to the top of the related group. Nowdays we are using RecyclerView to create our lists and there are times that we face our old problem: STICKY HEADER.

A few days ago, I encountered my old problem and googled it. There was an answer in StackOverFlow that helped me to solve my problem. So, I used this answer and after understanding the code and doing some modifications and adding some features (like supporting different header height size), I finally implemented Sticky Header RecyclerView.

Do you hurry to use your own Sticky Header?

If so, go to this address and use my library, but if you want to dig into what is happening behind the scene, stay with me.

So how to create sticky header?

The first step is creating a different view for our headers and a main view. We usually use getItemViewType() function in recyclerView for this goal. So your data should be a mix of header data and main data. I don’t want to go into details about how to insert different views in our recyclerView because you can find many examples which can help you. I’ve just shown you an instance for our purpose.

Your viewType can be Header or your main data. And then you bind related ViewHolder to your data:

So far so good. We’ve had this recyclerView until now:

Where is my Sticky Header?

Why should we use different view in our recyclerView? What is happening here? Lets go to step two.

We can’t force recyclerView to hold an item (Header). So we can draw an another view like our header to be on top of our rootView.‌ Therefore we need two things: 1.canvas to draw our header and 2.appropriate time for this action. onDrawOver() function is the right function we need. this function is in RecyclerView.ItemDecoration class. Thus we must create a class that extend RecyclerView.ItemDecoration and override onDrawOver() function and do our drawing.

First we check some condition. Then we get position and view for our header. in fixLayoutSize function we layout the top sticky header. In the following we are checking some condition to measure if next view is another header (getChildInContact() ), if so we should move old header and if not we just draw header. That is it.

Next we create an interface which our recyclerView must implements:

In our recyclerView, implement this interface:

Finally in your Fragment or Activity, you should just add created ItemDecoration class to your recyclerView.

Now we can enjoy the result:

final words

If your want full code of StickHeaderItemDecoration please go to this address. To help others find this article, please click ❤ to recommend. Thank’s in advance.

If you want to stay in touch with me, follow me on Linkedin.

Источник

Android recyclerview sticky headers

This project is no longer being maintained

This decorator allows you to easily create section headers for RecyclerViews using a LinearLayoutManager in either vertical or horizontal orientation.

Credit to Emil Sjölander for creating StickyListHeaders, a library that many of us relied on for sticky headers in our listviews.

Here is a quick video of it in action (click to see the full video):

Current version:

There are three main classes, StickyRecyclerHeadersAdapter , StickyRecyclerHeadersDecoration , and StickyRecyclerHeadersTouchListener .

StickyRecyclerHeadersAdapter has a very similar interface to the RecyclerView.Adapter , and it is recommended that you make your RecyclerView.Adapter implement StickyRecyclerHeadersAdapter .

There interface looks like this:

The second class, StickyRecyclerHeadersDecoration , is where most of the magic happens, and does not require any configuration on your end. Here’s an example from onCreate() in an activity:

StickyRecyclerHeadersTouchListener allows you to listen for clicks on header views. Simply create an instance of StickyRecyclerHeadersTouchListener , set the OnHeaderClickListener , and add the StickyRecyclerHeadersTouchListener as a touch listener to your RecyclerView .

The StickyHeaders aren’t aware of your adapter so if you must notify them when your data set changes.

If the Recyclerview’s layout manager implements getExtraLayoutSpace (to preload more content then is visible for performance reasons), you must implement ItemVisibilityAdapter and pass an instance as a second argument to StickyRecyclerHeadersDecoration’s constructor.

Item animators don’t play nicely with RecyclerView decorations, so your mileage with that may vary.

The header views aren’t recycled at this time. Contributions are most welcome.

I haven’t tested this with ItemAnimators yet.

The header views are drawn to a canvas, and are not actually a part of the view hierarchy. As such, they can’t have touch states, and you may run into issues if you try to load images into them asynchronously.

0.4.3 (12/24/2015) — Change minSDK to 11, fix issue with header bounds caching

0.4.2 (8/21/2015) — Add support for reverse ReverseLayout in LinearLayoutManager by AntonPukhonin

0.4.1 (6/24/2015) — Fix «dancing headers» by DarkJaguar91

0.4.0 (4/16/2015) — Code reorganization by danoz73, fixes for different sized headers, performance improvements

0.3.6 (1/30/2015) — Prevent header clicks from passing on the touch event

0.3.5 (12/12/2014) — Add StickyRecyclerHeadersDecoration.invalidateHeaders() method

0.3.4 (12/3/2014) — Fix issues with rendering of header views with header >

Читайте также:  Виджет обои для андроид

0.3.3 (11/13/2014) — Fixes for padding, support views without headers

0.3.2 (11/1/2014) — Bug fixes for list items with margins and deleting items

0.2 (10/3/2014) — Add StickyRecyclerHeadersTouchListener

0.1 (10/2/2014) — Initial Release

About

[UNMAINTAINED] Sticky Headers decorator for Android’s RecyclerView

Источник

Android RecyclerView Header tutorial will provide different examples like the below table.

Android RecyclerView With Header And Footer Example is what you are reading.

In this example, I will show you how to add sticky header and footer to the RecyclerView.

Android do not have built in method to make recyclerview with fixed header and footer.

While ListView have methods like addHeaderView() and addFooterView() methods which simplifies this process.

You may need to have fixed or sticky layout at the starting as well as ending point of the recyclerview to show useful information.

For example, the order summary window of the online food ordering app.

In this screen, you use recyclerview to show different food items with their name, quantity and price.

Here, you can show restaurant name at the header and total of price and quantity at the footer.

Step 1. Write Dependencies

Add the following lines in your build.gradle(Module:app) file

Above lines will enable us to use RecyclerView and CardView in our android studio project.

To make a fully customizable header and footer, we need to make XML files for both of them.

So make a new XML resource file under res->layout directory.

Name of this file should be rv_header.xml and add the below code in it.

I have taken one textview in this header file.

You can add imageview, videoview, button etc. UI widget to make it more attractive.

Now under same directory, create another XML file named rv_footer.xml

Write down following source code in rv_footer.xml

  • Again, I am adding just textview in this file. This file is also fully customizable and you can add styles and widgets to it.

Step 3. RecyclerView Specific File

Now it is time to make an XML file which helps to create views of every row of the recyclerview.

Make a new XML resource file under res->layout directory.

Give it a name single_item.xml and write the below code

  • I have written cardview code as a parent of the textview.
  • It will create a cardview section which makes recyclerview more attractive.

Step 4. Model Code

Let us create a model class for data maintenance.

Make a new JAVA class and give it a name HeaderModel.java

Following is the code block for HeaderModel.java

There are two types of data. One is the viewType and other is text.

viewType means a type of the item, whether it is header, footer or normal.

text means simply a value of the recyclerview item.

This class uses separate getter and setter methods for both variables.

Step 5. Adapter of RecyclerView

Adapter will help us to populate our RecyclerView in correct manner.

Prepare a new class named HFAdapter.java and add the below source code

Read the below code

First three integers are constants which stands for Header, Footer or Normal.

Then compiler will create object of LayoutInflater class.

Last line will create an arraylist of objects of HeaderModel class.

Look at the below constructor

  • Constructor will get context and arraylist into the parameter.
  • Then compiler will initialize them both.

This method will decide whether the row item is Header, Footer or Normal.

Look at the following code

Above method will inflate the required XML file to create the view of the row item.

If it is a header then compiler will inflate rv_header.xml , for footer rv_footer.xml, and single_item.xml for normal row.

Now read the below code

  • Compiler will check if the item at given position is header, footer or normal.
  • According to that if condition, compiler will set the text.

Step 6. Final Coding

We at the last part of this example. We will update activity_main.xml and MainActivity.java here.

Code block for activity_main.xml looks like the below

I have just taken one recyclerview in the main file.

Add the following code structure in MainActivity.java

Reading Main Activity

Consider the below source code

First one is making an object of the recyclerview.

Second is making the object of HFAdapter class.

Third one will create an arraylist with the objects of the HeaderModel class.

In onCreate() method, compiler will call dataSet() method.

Code for dataSet() method is as the following

This method generating the data to populate the arraylist.

Compiler will first run a for loop for the number of times equals to the number of recyclerview items + 2 (header and footer)

If the value if i is zero, it means that it is the first row of recyclerview.

Here, first row is the header of the recyclerview.

From second row to last second rows are the recyclerview items and here, compiler will execute the (else if) part.

Then, last row of the Recyclerview is the footer so compiler will execute the (else) part.

2. Android RecyclerView Sticky Header Like iphone | Pinned Header

Welcome to Android RecyclerView Sticky Header Like iphone Example.

We are going to develop a recyclerview with pinned headers in this tutorial.

You may have watched this concept of sticky or pinned header in iphone or ios.

Sticky header will stick at the top side of the recyclerview.

Now header can be one or more depending upon the type of the children items of recyclerview.

If there are more than one header, than header will be replace by another header when user scroll up all the items of the old header.

Android’s built in system do not provide any direct method or class to develop this kind of recyclerview.

So we need to use external github library in this example tutorial.

View RecyclerView

Step 1. Fetching Dependency

We will use one github library in this tutorial.

It will allow us to use some classes which are required in this example.

For this, add the below line in build.gradle(Modile:app) file

First line will integrate third party library.

Other one will fetch the required classes to use RecyclerView.

Step 2. Layout For Header And Children

In this example, we need to create two different layout XML files.

One will represent the header and another will represent children items.

Create a new file in res->layout directory and give it a name recycler_view_header_item.xml

Add the below code in recycler_view_header_item.xml file

  • Just one textview in the above file. You can also add imageview and other widget as per your requirements.
Читайте также:  Обзор планшетов lenovo android

Make another XML file named recycler_view_item.xml and copy the following in it

Step 3. New Interface

Create a new Interface and give it a name Section.java

Code structure for interface Section.java is as below

We will use this interface to create an arraylist with the objects of two different model classes.

Step 4. Models For Header And Child

Prepare a new JAVA class and name it as ChildModel.java

Write down the following coding lines in ChildModel.java

Now make another class named HeaderModel.java and code for it is as below

These model classes are useful for the maintenance of data while populating the RecyclerView.

Models are implementing Section interface and thus it also overrides all the methods of that interface.

Step 5. Section Adapter

Now it is time to write an adapter class for recyclerview.

Make a new class named SectionAdapter.java and write the following lines

Important methods of Adapter

In the constructor of this adapter, we are getting an arraylist with objects of the interface “Section

This arraylist contains the objects of both ChildModel and HeaderModel.

I will explain this arraylist in Main Activity, but for now we will just use it.

Consider the below code

Above method is inflating required XML file : recycler_view_header_item.xml or recycler_view_item.xml

If viewType is header than compiler will inflate recycler_view_header_item.xml file which is representing the header view.

Otherwise it will inflate the recycler_view_item.xml.

Read the following method

This method is setting the text in the textview.

Compiler will use isHeader() method (from interface) to decide whether the item is header or child.

And according to that, it will select the textview to write the name.

Step 6. Main Activity Files

Last but not least, let us make some necessary changes in the main files.

Source Code block for activity_main.xml should look like the below

  • In this file, I have just taken one recyclerview.

In the MainActivity.java file, write the following source code

Going Inside Main Activity

Consider the below source code

Second line is creating an arraylist of the objects of the Section Interface.

First line is making a string array which contains the types of the vehicles.

This string array will provide the headers of the RecyclerView.

Third line is also making one string array which is giving us children names for our RecyclerView.

Read the following

First one is simply initializing the arraylist.

Second one is calling a method populateList()

Code block for populateList() is as the below

In this method, compiler will create one for loop with 26 iterations.

26 is the number equal to the number of children items + header items.

You should change this number as per the number of children items + header items. in your project.

if condition ( if(i == 0 || i == 5 | i == 10 | i == 15) ) is true when there are headers.

At this time, compiler will create the object of the HeaderModel class and will add it to the arralist.

When the if condition is false, compiler will create the object of the ChildModel class and will add it to the arraylist.

Finally, above code will create an object of the adapter class.

And then it will add the adapter object to the RecyclerView.

3. Android RecyclerView Multi Column With Sticky Header Example Tutorial

Today’s bright topic is about Android Recyclerview Multi Column With Sticky Header.

We will create one example with android studio in this tutorial. You will learn to make android cardview with two or more columns.

Multi column recyclerview means that every single row item is having more than one column.

This type of recyclerview creates a table like structure.

In many occasions, you want to make a layout where there are one or more sticky headers and then a table like structure.

For example, to show an order summary at restaurant app, you may have static headers like name of the restaurant.

After that you will show an order in the tabular form using recyclerview.

Here, this tutorial will help you get your goal.

Final UI

Now follow all the below steps to create this example.

Step 1. Having Dependencies

We are going to use recyclerview and cardview here. So we need to add it’s dependencies in

build.gradle(Module :app) file.

Write below lines in build.gradle(Module :app) file.

Above lines will download necessary classes for recyclerview and cardview.

Step 2. Making Recycler Item File

Now we will create one layout file. This file will generate the view structure for each row of recyclerview.

Create a new file named recycler_item.xml in res->layout directory.

Copy the following source code in recycler_item.xml

In the above code, I have taken as a parent of the main layout. It will generate card structure.

Under this cardview tag, I have taken one Linearlayout with horizontal orientation.

Now, I have set two Textviews horizontally under this linearlayout.

First textview is for product name and second is for product quantity.

Step 3. Making Food Model

The main purpose behind creating model class is to have proper data set to populate the recyclerview.

Prepare a new java class named FoodModel.java

Add the below code in FoodModel.java

  • Above structure includes getter and setter methods for two variables.
  • One variable is for product name and another is for quantity.

Step 3. Preparing Adapter

Let us create adapter class which will provide data to populate the recyclerview.

Make a new java class named FoodAdapter.java

Write down the following coding lines in FoodAdapter.java

Going through above class

First of all, read the below code

It is the constructor of the adapter class.

It receives context and arraylist from first and second parameter respectively.

ArrayList contains the objects of the FoodModel class.

Consider the next coding lines

  • Above method will inflate the recycler_item.xml file which we created in Step 2.
  • Compiler will create layout using this recycler_item.xml file for every row.

Step 4. Final Changes in Main Classes

Last thing is to update activity_main.xml and MainActivity.java files.

Replace the existing code of activity_main.xml with the below lines

Here, I have taken two textviews at the top and then one linearlayout with horizontal orientation.

First textview is showing the name of the restaurant and second one is the heading of the page.

After linearlayout I have defined our recyclerview.

Now it is time to write the MainActivity.java as per below code

Measuring Above Code

Following are the definitions of the required objects.

First line is making a string array named Products. It includes various product names.

Second line is creating an integer array which holds the quantity of the products.

Third line will prepare an arraylist (foodModelArrayList) with the objects of the FoodModel class.

Читайте также:  Android sdk что такое eclipse

Last line will simply make an object of recyclerview.

Consider the below line

  • Above line is setting the data in to the foodModelArrayList.
  • Compiler will use populateList() method to generate the data.

Above lines are making the populateList() method.

Here, Compiler will create one for loop with seven iterations.

During every iteration, it will create one object of FoodModel class. Then it will set the product name and quantity to that object.

After this, compiler will simply add that object in the arraylist.

4. Android RecyclerView Section Header Example | Group By Header

Android RecyclerView Section Header Example is the hot topic of today.

We will create a recyclerview which has specific headers among it’s various child items.

Last Output

Section Header

Section header is a particular row item which can categorized recyclerview’s child items.

For example, you are making recyclerview with vehicle’s manufacturer company names.

Here, you can categorize company names with categories like Cars, Bikes, Air crafts etc.

In the first row you will write “Cars” and in the second and third row, you may write “Mercedes” and “Audee“.

In the fourth row you give section header named “Bikes” and you put “Honda” and “Ducati” in Fifth and sixth row of recyclerview. This process continues til the end.

In this example, we will create a recyclerview where all the section header have different layout structure than the normal child row items.

Let us go through all the steps.

Step 1. Build.gradle(Module: app)

We have to add gradle lines to import the required classes of recyclerview and cardview.

Write following in the build.gradle(Module: app) file

Step 2. Drawable files

Create a drawable resource file named cardview.xml under res->drawable directory

Copy the following code in cardview.xml

Above file will create specific background for the section header row.

I have given gradient effect with green color shadows in this file.

Make another file named cardview_child.xml and add following code

  • cardview_child.xml file will create the particular background for child rows of recyclerview.

In this file, purple color gradients will make child row more colorful.

Step 3. RecyclerView Row resources

Now we need to create two layout resources file. One for header row and one for child row.

Make a new layout resource file and name it “rv_header.xml” and add the below source code

This “rv_header.xml” file will create a layout structure for header file.

Now create another layout resource file named “rv_child.xml”. Following code is for this file.

Every child row will use the above code to create it’s layout structure.

Step 4. Model Classes

Create a new class named HeaderModel.java

Add the below source code in it

This class contains necessary methods regarding headers of the recyclerview.

In the above code, isHeader() and getName() methods are override because this class implements the ListItem interface which is written in the Main Activity.

isHeader() method returns the boolean value. If the the object is of the HeaderModel class, then it will return true otherwise false.

getName() method will return the name of the string whether it is vehicle type or manufacturer, it does not matter here.

(You will see the use of these two above methods in the adapter class later in this tutorial)

setHeader() method is used to set the name of the header.

Now create a new class and give it a name “ChildModel.java”

Put following code in it

All three methods present in the above class are similar with the methods of HeaderModel class.

The text which is set and get by various methods are of the child rows name, while in HeaderModel class, the text was about header name.

Step 5. Writing Main Activity

You need to change the Main activity’s code now.

Add below code in activity_main.xml

I have taken recyclerview in the main layout.

Write down the following source code into MainActivity.java class

Understanding above code

Read the below lines

There are two string array variables are there.

First string array variable called vehicleTypes represents the types of the vehicles. These vehicle types are the headers of the recyclerview.

Second string array variable called childnames contains the names of the vehicle manufacture companies. These names are the child rows of the recyclerview.

Interface

HeaderModel.java and ChildModel.java were implementing the ListItem interface. This interface is defined here in the Main Activity.

Following is it’s coding lines

It contains two methods so both HeaderModel.java and ChildModel.java classes were overriding these methods.

Populating RecyclerView Data

Our data for header and child rows are present in the two strings variables as we have just shown above.

Now we need to convert this data in the arraylist of interface objects to pass them into the adapter class.

Following method will do this for us

In the RecyclerView, first row will represent the Header name. Then next four rows will be child rows.

As per this calculations, First, Sixth, eleventh and sixteenth rows of the recyclerview will be the header.

So in the above code, if condition will be true for First, Sixth, eleventh and sixteenth iterations of the for loop.

When the if condition is true, an object of the HeaderModel class is created, populated with the name and then it is inserted into the arraylist of interface (which is listItemArrayList).

When the if condition is false, an object of the ChildModel class is created, populated with name and then it is inserted in the arraylist of interface (which is listItemArrayList).

After the successful call of the populateList() method, listItemArrayList passed into the constructor of the Adapter class using below lines

Step 6. Custom Adapter

Now finally, we are at the adapter class to fill the recyclerview.

Create a new class named CustomAdapter.java

Add the below code in it

Explanation

Read the below code

We are deciding whether the view of the row should be header view or child view in the above method.

We are using isHeader() method for this purpose.

LAYOUT_HEADER and LAYOUT_CHILD are the integer constants.

Consider below codes of classes

Two classes are defined in the above code.

First one represents the Header and second one is for Child row.

We are just declaring the textviews for header and child row in the above classes.

Now consider the following code

We will set the textview value in onBingViewHolder method.

Here I have checked one if condition. When the if condition is true, textview(tvHeader) which defined in the MyViewHolderHeader class will get the value.

When the if condition is false, textview(tvchild) which defined in the MyViewHolderChild class will get the value.

Источник

Оцените статью