filtering listviews like the contacts app

I thought it would be nice to provide filtering capabilities in my ListViews – they could get long. It would be nice if this was kind of done automatically for you when you put android:textFilterEnabled=”true” on the ListView, but this is not the case; I suppose in the end it’s better to have to be explicit about exactly what’s being filtered and how, and this is Java after all.

Enabling a filter as above just enables the view to gather text the user types; it doesn’t actually do anything with it unless I set up the adapter to use it. I got a pointer from this thread. My ListAdapter is a subclass of SimpleCursorAdapter so all I had to do in my ListActivity is:

  adapter.setFilterQueryProvider(this);
  // implement FilterQueryProvider
  public Cursor runQuery(CharSequence constraint) {
        Cursor cur = mDba.fetchTrackers(mCurrentGroupId, constraint.toString());
        startManagingCursor(cur);
        return cur;
  }

I’m really hoping this doesn’t leak cursors or something. Anyway, having properly implemented fetchTrackers such that it returns a filtered query, that’s all there is to it – typing next now filters the list items.

Next problem: what happens when I type in a filter, select an item to start another activity, and then return? In the Contacts app (my model for this), the filter actually remains in place, which is a little odd. In my app, the filter *text* remains, but the items in the list are not filtered unless I start typing again! Very odd. I would like to either clear the filter or have the persistent filter applied when I resume the Activity.

There’s pretty much zippo on d.android.com about this. A Google search found me this interesting tidbit – not actually relevant to my problem I don’t think but it gives me a lead on something else I discovered the other day: if I used an alternate IME (say the chinese one) on a textfield, the text entered didn’t seem to get through to the OnKeyListener I set on the EditText. I’ll have to try a TextWatcher.

So anyway, my best bet is probably looking through the Contacts app – open source, right? Yay. Except I sometimes wonder if making something open source leaves less incentive to provide decent documentation. In any case, a quick look through the Contacts app didn’t yield any clues and I’m gonna have to stop for the night.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: