Android ListView SectionIndexer and fast scroll

This tutorial describes how to use Android ListView SectionIndexer to enable fast search. Android ListView has a method that enables the fast scroll called setFastScrollEnabled. To enable Android ListView SectionIndexer, we have to pass true value to our Android Adapter and it must implement SectionIndexer. I want to create a custom component using Android ListView SectionIndexer so that i can move fast along the ListView items selected by the first letter.

In other words, i would like to obtain something as shown in the picture below:

When the user touches the screen on the fast scroll bar area, moving his finger up and down, then the ListView scrolls to the first item starting with the letter selected by the user in the scroll bar. Otherwise when user moves his finger outside the scroll bar the listview scrolls as always.
So let’s start. The first thing we need to create a custom component derived from android.widget.ListView, we call it FastSearchListView. This component behaves like a “normal” ListView and adds on the right side the scroll bar as shown in the picture above. The code by now is very simple:

Now we have to override the onDraw method to change the ListView standard component behaviour. By now we can suppose that we have an array of strings representing the alphabet letters from a…z. So the onDraw method looks like:

What we do here it is quite simple. In the first lines we calculate the real width of the scroll bar and the starting point along x axis. Then we draw a rectangle (canvas.drawRect) with a semi transparent background. The next step we need to get the indexSize, it means how big it is the space between each letter. The last step is write the letters inside the rectangle (scroll bar). To make this example working you need to create and adapter i called SimpleAdapter. I have derived this adapter from ArrayAdapter. If you want more information about it you can refer to this post.

Running this example you have:

Android Listview SectionIndexer and adapter

As we told before we have a custom adapter derived from ArrayAdapter and we need a way to handle the fast scroll. As the android documentation says we need to implements a SectionIndexer interface.Our custom adapter then must implement this interface. Without digging into the details of our custom adapter we can focus our attention on the methods required by this interface. Let’s suppose that sections are defined as

The first method getPositionForSection simply retrieves the position inside the listView given a section index. In our case it is quite simple because to know the listview position we have to find the first item that starts with the letter corresponding to the section index. If we suppose that our section index string is a simple string from a to z to obtain the letter we can simply use getCharAt. Then we iterate over the listview items and find the first one starting with this letter.

The other method getSectionForPosition is not implemented because we don’t use it.

The last one getSections simply converts our string index in an array of objects. We will use this method in our custom listview. In the custom component when we set the adapter, we simply create a string array with all sections.

Handle Touch Event Inside and Outside the Scroll bar

Now we have to handle the touch events so that when the user touches outside the scroll bar area our custom component behaves like a normal list view and when user touches inside the scroll bar are we have to handle this “touch” in other way. To know it we can simply retrieve the x coord touch position and compares it against sx value (see the code above). If x is greater than sx then we touches the scroll bar otherwise we touched the list. To know which letter we touched we have to know the y coord touch position and divide it with the indexSize. After we know the index inside the sections using that simple conversion, we use the SectionIndexer method getPositionForSection to get the item position inside the listView. We can then override the onTouch method in our custom component like that:

Beatify the Listview

Once we made Android Listview sectionindexer and make it working as expected, we can make some improvements to our custom list view. For example one simple thing we can do is showing the selected letter in the middle of the screen. This can be done quite easily modifying the onDraw method so that it shows the selected index letter. We can add this piece of code inside the onDraw method:

Now when the user moves up his finger, we have to hide after some time this letter. It can be done in two steps: first we intercept the MotionEvent.ACTION_UP event and then we send a message to an handler that removes this letter. So the onTouchEvent method becomes:

About The Author

I'm an electronic engineer with over 15 years of
experience in computer programming. I'm the author of the book "Android things projects". I'm a MVB at DZone and DZone Guide Author. I have contributed to the IoT guide. I'm the technical reviewer of the book Internet of Things with Arduino Blueprints(published by PacktPub). I love creating IoT projects using Arduino, Raspberry Pi,
Android, and other platforms. I am interested in the convergence
between IoT and the mobile applications. I'm SCEA, SCWCD, and SCJP
certified.
Follow on: Twitter | Linkedin

Anonymous

Getting message – This page is taking too long to load

survivingwithandroid

I'm sorry if it takes too muc time to load.

Anonymous

Thanks it works now. Now, the problem is that I have implemented this list view in an android dialog and on clicking the list item it doesn't close the dialog. It is not even calling the onclick event of list view. Not sure if it is clashing with onTouchEvent?

survivingwithandroid

I'm interested on your comment because i didn't consider this aspect, using the listview in a dialog. I will test it. If you can you can send to me the skeleton you are using so that i can do it faster.

Anonymous

so basically I have created a custom spinner which when you click on opens the dialog with list view on it. Now when you select item it should close the dialog and selects the spinner with the selected option. If you comment the onTouchEvent() method, it works fine but I want to implement both of the functionalities in my custom spinner.

The spinner implements DialogInterface.OnClickListener and so I have overridden onClick event

@Override

public void onClick(DialogInterface dialog, int which) {

setSelection(which);

dialog.dismiss();

}

gnichola

Thanks for the example. One bug I came across was currentPosition, in FastSearchListView, would go out of bounds if I tapped or dragged off the top or bottom of the screen. I modified the code to bound currentPosition to [0..sections.length] like so:int currentPosition = (int) Math.floor(y / indexSize);currentPosition = Math.max( 0, currentPosition );currentPosition = Math.min( sections.length, currentPosition );

survivingwithandroid

Thx for your suggestion. I will try to reproduce the error and then i will modify the code. Thx for your support again.

Đức Quỳnh

Sorry our author, I have a wondering here. When I stroke to the customized listview (Up or Down) it scrolls a small distance. That's not as smooth as the original listview. So, what do I have to do to make it smooth like the original?

Mahesh Makavana

please upload code for indexbar dynamic set fullscreen all A to Z allphabets in screen ?

Michael Kamen

Something weird is happening with the timeout of the letter that is painted on the screen.It's about this code:listHandler.sendEmptyMessageDelayed(0, 30 * 1000);private class ListHandler extends Handler {

If you make currentPostion to a classmember instead, you can then in the onDraw() method do this:
for(int i = 0; i < sections.length; i++) {
if(i == currentPosition) {
….
}
}
to make something to mark the chosen letter, and then make a custom OnScrollListener, and put this is onScroll():
if(sections != null && isFastScrollEnabled()) {
RelativeLayout childView = (RelativeLayout) getChildAt(0);
String letter = ((TextView)childView.findViewById(R.id.tv_title)).getText().toString().substring(0, 1);

If you make currentPostion to a classmember instead, you can then in the onDraw() method do this:for(int i = 0; i < sections.length; i++) { if(i == currentPosition) { …. }}to make something to mark the chosen letter, and then make a custom OnScrollListener, and put this is onScroll():if(sections != null && isFastScrollEnabled()) { RelativeLayout childView = (RelativeLayout) getChildAt(0); String letter = ((TextView)childView.findViewById(R.id.tv_title)).getText().toString().substring(0, 1);

Sorry our author, I have a wondering here. When I stroke to the customized listview (Up or Down) it scrolls a small distance. That’s not as smooth as the original listview. So, what do I have to do to make it smooth like the original?

Rajkumar Ramanathan

Sorry our author, I have a wondering here. When I stroke to the customized listview (Up or Down) it scrolls a small distance. That's not as smooth as the original listview. So, what do I have to do to make it smooth like the original?

Android Developer

Though it looks nice, I don’t think this method can support all cases. For example, what if there are more than the English alphabet to show?
It will get very condensed and un-readable. I prefer the way that default fast-scroller is shown.
I’ve also made a POC to show how to do it like the Lollipop’s contacts app, here:https://github.com/AndroidDeveloperLB/LollipopContactsRecyclerViewFastScroller

What I’d like to know is how to do the same for ListView, and also maybe customize it to look like the way it looks on Lollipop (including the bubble).

Android Developer

Though it looks nice, I don't think this method can support all cases. For example, what if there are more than the English alphabet to show?It will get very condensed and un-readable. I prefer the way that default fast-scroller is shown.I've also made a POC to show how to do it like the Lollipop's contacts app, here: https://github.com/AndroidDeveloperLB/LollipopContactsRecyclerViewFastScroller

What I'd like to know is how to do the same for ListView, and also maybe customize it to look like the way it looks on Lollipop (including the bubble).

Sudheer

I did implemented this. Now I cant set the height of list view. It takes fullscreen view. It covers a button below it. Is there any way to set margin for this lisview? Thanks

Sign up for our Newsletter

Enter your email and stay on top of things,

Get SwA updates delivered to your inbox. Article, tips, source code

×

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.