Tuesday, December 4, 2012

Android ListView with SectionIndexer and fast scroll

In this post i want to analyze how to use ListView with SectionIndexer enabling the fast search. ListView has a method that enables the fast scroll called setFastScrollEnabled. If we pass a true value our Adapter must implement SectionIndexer. I want to create a custom component using ListView and 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:

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 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:
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;

}
.....
}

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:
@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);


}
}

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_preview

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
private static String sections = "abcdefghilmnopqrstuvz";

then we have
....
@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 < sections.length(); i++)
sectionsArr[i] = "" + sections.charAt(i);

return sectionsArr;

}

.....

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.
@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
if (adapter instanceof SectionIndexer)
sections = (String[]) ((SectionIndexer) adapter).getSections();
}

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:
@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);
}

 


BEAUTIFY THE LISTVIEW


Once we made everything 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:
// 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);
}

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:
listHandler = new ListHandler();
listHandler.sendEmptyMessageDelayed(0, 30 * 1000);

and the ListHandler is shown below:
private class ListHandler extends Handler {

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


}

Source code here.



Android ListView with SectionIndexer and fast scroll Rating: 4.5 Diposkan Oleh: Unknown

0 comments:

Post a Comment