Android development blog
Tutorials about Android dev topics

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.

9 comments:

  1. Getting message - This page is taking too long to load

    ReplyDelete
  2. survivingwithandroidApril 9, 2013 at 3:50 PM

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

    ReplyDelete
  3. 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?

    ReplyDelete
  4. survivingwithandroidApril 10, 2013 at 9:44 AM

    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.

    ReplyDelete
  5. 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.

    I have overridden performClick method of spinner

    @Override

    public boolean performClick(){

    Context context = getContext();

    SpinnerDialog lDialog = new SpinnerDialog(context, getSelectedItemPosition(), (ListAdapter) getAdapter(), this);

    lDialog.show();

    lDialog.getWindow().setLayout(400, 600);

    return true;

    }



    This is the spinner dialog class





    public class SpinnerDialog extends Dialog implements AdapterView.OnItemClickListener {



    DialogInterface.OnClickListener mListener;

    DigListView listView;



    SpinnerDialog(Context inContex, int inPosition,

    ListAdapter inSpinnerAdapter,

    DialogInterface.OnClickListener inListener) {



    super(inContex);



    this.setContentView(R.layout.activity_listview);

    this.setTitle("Select Item"); // Can get from the displayname property



    mListener = inListener;



    listView = (DigListView) findViewById(R.id.listview);

    listView.setAdapter(inSpinnerAdapter);

    listView.setOnItemClickListener(this);

    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    listView.setSelection(inPosition);

    }



    @Override

    public void onItemClick(AdapterView inParent, View inView, int inPosition, long inId) {

    if(mListener != null) {

    mListener.onClick(this, inPosition);

    }

    }

    }





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



    @Override

    public void onClick(DialogInterface dialog, int which) {

    setSelection(which);

    dialog.dismiss();

    }

    ReplyDelete
  6. 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 );

    ReplyDelete
  7. survivingwithandroidAugust 19, 2013 at 9:24 PM

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

    ReplyDelete
  8. 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?

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

    ReplyDelete

Related Posts with Thumbnails