On Android, how can I a ListView
that filters based on user input, where the items shown are updated dynamically based on the TextView
value?
I'm looking for something like this:
-------------------------
| Text View |
-------------------------
| List item |
| List item |
| List item |
| List item |
| |
| |
| |
| |
-------------------------
running the programm will cause a force close.
I swaped the line:
with
could that be the problem? What is the '@+building_list' for?
First, you need to create an XML layout that has both an EditText, and a ListView.
This will lay everything out properly, with a nice EditText above the ListView. Next, create a ListActivity as you would normally, but add a
setContentView()
call in theonCreate()
method so we use our recently declared layout. Remember that we ID'ed theListView
specially, withandroid:id="@android:id/list"
. This allows theListActivity
to know whichListView
we want to use in our declared layout.Running the app now should show your previous
ListView
, with a nice box above. In order to make that box do something, we need to take the input from it, and make that input filter the list. While a lot of people have tried to do this manually, mostListView
Adapter
classes come with aFilter
object that can be used to perform the filtering automagically. We just need to pipe the input from theEditText
into theFilter
. Turns out that is pretty easy. To run a quick test, add this line to youronCreate()
callNotice that you will need to save your
ListAdapter
to a variable to make this work - I have saved myArrayAdapter<String>
from earlier into a variable called 'adapter'.Next step is to get the input from the
EditText
. This actually takes a bit of thought. You could add anOnKeyListener()
to yourEditText
. However, this listener only receives some key events. For example, if a user enters 'wyw', the predictive text will likely recommend 'eye'. Until the user chooses either 'wyw' or 'eye', yourOnKeyListener
will not receive a key event. Some may prefer this solution, but I found it frustrating. I wanted every key event, so I had the choice of filtering or not filtering. The solution is aTextWatcher
. Simply create and add aTextWatcher
to theEditText
, and pass theListAdapter
Filter
a filter request every time the text changes. Remember to remove theTextWatcher
inOnDestroy()
! Here is the final solution:i had a problem with filtering, that results have been filtered, but not restored!
so before filtering (activity start) i created a list backup.. (just another list, containing the same data)
on filtering, the filter and listadapter is connected to the primary list.
but the filter itself used the data from the backuped list.
this ensured in my case, that the list was updated immediately and even on deleting search-term-characters the list gets restored successfully in every case :)
thanks for this solution anyways.