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 a true value to our Android Adapter and it must implement SectionIndexer. I want to create a custom component using Android ListView SectionIndexer so that we can move fast along the ListView items selected by the first letter.

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

android_listview_sectionindexer
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 a 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:

[java]public class FastSearchListView extends ListView {
private Context ctx;
private static int indWidth = 20;
private String[] sections;
private float scaledWidth;
private float sx;
private int indexSize;
private String section;

public FastSearchListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
ctx = context;
}

public FastSearchListView(Context context, AttributeSet attrs) {
super(context, attrs);
ctx = context;
}

public FastSearchListView(Context context, String keyList) {
super(context);
ctx = context;
}
…..
}[/java]

Now we have to override the onDraw method to change the ListView standard component behavior. 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:

[java]@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
scaledWidth = indWidth * getSizeInPixel(ctx);
sx = this.getWidth() – this.getPaddingRight() – scaledWidth;

Paint p = new Paint();
p.setColor(Color.WHITE);
p.setAlpha(100);

canvas.drawRect(sx, this.getPaddingTop(), sx + scaledWidth,
this.getHeight() – this.getPaddingBottom(), p);

indexSize = (this.getHeight() – this.getPaddingTop() – getPaddingBottom())
/ sections.length;

Paint textPaint = new Paint();
textPaint.setColor(Color.DKGRAY);
textPaint.setTextSize(scaledWidth / 2);

for (int i = 0; i < sections.length; i++)
canvas.drawText(sections[i].toUpperCase(),
sx + textPaint.getTextSize() / 2, getPaddingTop()
+ indexSize * (i + 1), textPaint);
}
}[/java]

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 to write the letters inside the rectangle (scrollbar). 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

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

[java] <pre>private static String sections = "abcdefghilmnopqrstuvz";
[/java]

then we have

[java]….
@Override
public int getPositionForSection(int section) {
Log.d("ListView", "Get position for section");
for (int i=0; i < this.getCount(); i++) {
String item = this.getItem(i).toLowerCase();
if (item.charAt(0) == sections.charAt(section))
return i;
}
}
return 0;
}

@Override
public int getSectionForPosition(int arg0) {
Log.d("ListView", "Get section");
return 0;
}

@Override
public Object[] getSections() {
Log.d("ListView", "Get sections");
String[] sectionsArr = new String[sections.length()];
for (int i=0; i &lt; sections.length(); i++)
sectionsArr[i] = "" + sections.charAt(i);
return sectionsArr;
}

[/java]

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 into 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.

[java]@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
if (adapter instanceof SectionIndexer)
sections = (String[]) ((SectionIndexer) adapter).getSections();
}
[/java]

Handle Touch Event Inside and Outside the Scrollbar

Now we have to handle the touch events so that when the user touches outside the scrollbar area our custom component behaves like a normal list view and when a user touches inside the scroll bar are we have to handle this “touch” in another 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 touch 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:

[java]@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
if (x < sx)
return super.onTouchEvent(event);
else {
// We touched the index bar
float y = event.getY() – this.getPaddingTop() – getPaddingBottom();
int currentPosition = (int) Math.floor(y / indexSize);
section = sections[currentPosition];
this.setSelection(((SectionIndexer) getAdapter())
.getPositionForSection(currentPosition));
}
break;
}
case MotionEvent.ACTION_MOVE: {
if (x < sx)
return super.onTouchEvent(event);
else {
float y = event.getY();
int currentPosition = (int) Math.floor(y / indexSize);
section = sections[currentPosition];
this.setSelection(((SectionIndexer) getAdapter())
.getPositionForSection(currentPosition));
}
break;
}
}
return super.onTouchEvent(event);
}[/java]

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:

[java]// We draw the letter in the middle
if (showLetter && section != null && !section.equals("")) {

Paint textPaint2 = new Paint();
textPaint2.setColor(Color.DKGRAY);
textPaint2.setTextSize(2 * indWidth);
canvas.drawText(section.toUpperCase(),
getWidth() / 2, getHeight() / 2,
textPaint2);
}
[/java]

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 a handler that removes this letter. So the onTouchEvent method becomes:

[java]listHandler = new ListHandler();
listHandler.sendEmptyMessageDelayed(0, 30 * 1000);[/java]

and the ListHandler is shown below:

[java]private class ListHandler extends Handler {

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
showLetter = false;
FastSearchListView.this.invalidate();
}
}[/java]


Summary

At the end of this post, you gained the knowledge how to use Android ListView with SectionIndex.

    1. Anonymous April 9, 2013
    2. survivingwithandroid April 9, 2013
    3. Anonymous April 9, 2013
    4. survivingwithandroid April 10, 2013
    5. Anonymous April 10, 2013
    6. gnichola August 12, 2013
    7. survivingwithandroid August 19, 2013
    8. Đức Quỳnh April 17, 2014
    9. Mahesh Makavana June 26, 2014
    10. Michael Kamen December 6, 2014
    11. Michael Kamen December 7, 2014
    12. Michael Kamen December 6, 2014
    13. Tobbbe January 14, 2015
    14. Tobbbe January 14, 2015
    15. Rajkumar Ramanathan March 11, 2015
    16. Rajkumar Ramanathan March 11, 2015
    17. Android Developer April 7, 2015
    18. Android Developer April 6, 2015
    19. Sudheer April 19, 2016
      • Francesco Azzola April 19, 2016
        • Sudheer K April 20, 2016

    Add Your Comment