Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Header View (not Section Header) of ListView Stick on Top

I have a ListView with a HeaderView.

I want one of the views in the HeaderView to stick on top.

I've seen a lot of examples for sticky Section Headers.

I also looked at StickyScrollViewItems but since I'm using a ListView, I cannot use a ScrollView.

Is there a library available for this or should I just override the OnScrollListener of the ListView?

Thanks.

like image 794
dannyroa Avatar asked Nov 01 '22 16:11

dannyroa


2 Answers

I have just written a load of code that does this that I cant share for contractoral reasons. Basically follow the approach outlined here and apply to a listview rather than a scroll view.

Main points are

  1. Create a wrapper view that contains your floating/sticky header and your listview as siblings
  2. Use a proxy method when adding headers with an isSticky boolean - if is sticky then add a fake blank header to the listview of the same size and your intended header view to the floating header wrapper (use a relative layout here)
  3. Set a scroll listener of the listview that tracks the top px position of the dummy header view in the list and setting this as a top margin of the floating header that sits inside a relative layout
  4. Handle all the annoying edge cases / OEM overscroll crap to get it to work in all situtions (like this for samsung)

Remember to set the initial position of the floating/pinned header after the listview has been layed out.

I feel its a little bit involved and takes some tweaking to get right - this is a time where i envy iOS and any iOS devs will think your slacking as it takes a while to implement :D

All the Open libs out there at time of writing are using scroll views or list view headers. This issue with these approaches are that list views recycle views (so unlike scroll views you cant just keep a ref to the dummy view) and also the current libs seem duplicate the sticky views using adapter getView methods and so on - which is no good for dynamic list view header views as they are not recycled and can only have one parent, so reparenting would be annoying (and in my case has a lot of functionality so I defo dont want to create two views of the same type and shoehorn the current libs to fit my solutions)

like image 82
Dori Avatar answered Nov 15 '22 06:11

Dori


I don't know of any library that lets you do this but what I do for a header is to use a RelativeLayout for my xml that will have the ListView. Then create your header view however you want and give it the property

android:layout_alignParentTop="true"

then give your ListView

android:layout_below="@id/idOfHeaderView

This is the easiest way I know of to dock a header view at the top. It has worked for me every time. I hope this helps.

like image 24
codeMagic Avatar answered Nov 15 '22 05:11

codeMagic