Android Tutorial – ListView with “sticky” headers

Using emilsjolander sticky listView can be a little tricky. This tutorial will show you how to use it with an alphabetically sorted list. First off, go to your build.gradle and add the next line to your dependecies:

    compile 'se.emilsjolander:stickylistheaders:X.X.X'

You can grab the latest version X.X.X from the github page here:
Now add a new view to your layout:

    <se.emilsjolander.stickylistheaders.StickyListHeadersListView
        android:id="@+id/awesome_list_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

If you want the user to see the current category when scrolling (that little thumbnail picture with the current letter) then enable fast scrolling:

        awesomeListView = (StickyListHeadersListView) findViewById(R.id.awesome_list_view);
        awesomeListView.setFastScrollEnabled(true);

In our adapter we are going to use a hash map to remember the position of the scroll cursor for each header.

    private HashMap<String, Integer> indexer;

    private void initIndexer() {
        indexer = new HashMap<>();

        Collections.sort(currentItems);

        for (int i = 0; i < currentItems.size(); i++) {
        	//remember only the first time when we found the header [1]
            if(indexer.get(currentItems.get(i).toUpperCase().charAt(0) + "") == null)
            {
                indexer.put(currentItems.get(i).toUpperCase().charAt(0) + "", i);
            }
        }

        Set<String> keys = indexer.keySet();
        currentHeaders = new ArrayList<>(keys);
        Collections.sort(currentHeaders);
    }

[1] – in case we have the following list:
abc
agd
ahgy
akuuy
ajhjg
basd
brgee
bgrer
The indexer will remember the position 0 for ‘a’, and position 5 for ‘b’, so between 0 and 5 the header will be ‘a’.

If you see the scrolling not working as it should, then you messed up your indexer.

Github repo with the full code can be found here:

Leave a Reply

You must be logged in to post a comment.