Android ListView with Sticky Header

This tutorial explains how to keep the specified view sticked to the top during scroll of the list.
The behavior is shown in below image.

As seen here, while the list is scrolled, the header content of top row remains visible until that row leaves the screen.

Here are the steps.
First of let’s create a row layout.

@+id/header is the header part of this view. And the @+id/content is displaying the main text content. Header is on top of the content layout. Since the header text and context can overlap each other, I added empty view to content layout above the text. This empty view’s height is same with the header’s height. So this positions the text content properly below of the header view. To make this header part to remain on it’s palce during scroll, we need our own scroll listener for the listview. The scroll listener would be like this


Whenever user starts scrolling, the methods above called.
The main logic is to get the first visible element’s header and calculate if that row has place to keep the header visible during scroll.

You can check a running code at https://github.com/basarbk/Tutorials
I added a custom ListView which deals with the scroll logic.
https://github.com/basarbk/Tutorials/blob/master/app/src/main/java/com/bafoly/tutorials/view/ListViewStickyHeader.java

Have fun!.

Leave a comment