5.4 Searching in a List View
If we wanted to search for an item within a
ListView
, we would have to somehow get input from the user which is something we can do with a specific view type.The
EditText
will allow us to get user input we can then filter our list with.
EditText example
Once we have an
EditText
we can create an addTextChangedListener
to it to customize the behavior on such actions:editText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
// requery/filter your adapter then set it to your listview
}
})
The above code has 3 overridden functions:
afterTextChanged
- This method is called to notify you that, somewhere within
s
, the text has been changed.
beforeTextChanged
- This method is called to notify you that, within
s
, thecount
characters beginning atstart
are about to be replaced by new text with lengthafter
.
onTextChanged
- This method is called to notify you that, within
s
, thecount
characters beginning atstart
have just replaced old text that had lengthbefore
.
onTextChanged
is the method in which we will requery our adapter and then set it to our list view to change the results of what is displayed after searching; effectively searching.Last modified 2yr ago