I have a fragment pager that pages between instances of the same Fragment
. On top of those fragments, a search function is implemented via a SearchView
in the App bar. The user should be able to search individually in each of these fragments.
The search function filters an ArrayList
that displays the current items. Most of the search filter functions work as expected, but I am running into this problem:
When the user is searching but then swipes to the next page, the search bar (as expected) disappears, but the keyboard stays on screen. This means that the search wasn't properly cleared and cancelled. Going back to the previous view also shows that the filter is still active. The user needs to restart the search process and then cancel it to view the list correctly again.
The problem is demonstrated in this video.
What are ways to circumvent this problem? I am currently thinking about two options:
1 - On page change, clear the search function
This does work, however it doesn't automatically get rid of the keyboard and doesn't handle other problems like switching to another Activity
while searching is active.
2 - Figure out a way to be notified that the search was canceled
This would be the optimal way, but I haven't figured out how to do it. Sadly, SearchView
's OnCloseListener
only reacts to the conventional way of closing the SearchView
, so I can't use that.
Thanks in advance for your help, I'm looking forward to your suggestions.
So I didn't figure out a fix, but I did manage to get an event when the view is cancelled. I am getting the event when the search dropdown is attached or detached by adding a OnAttachStateChangeListener
, as suggested by https://stackoverflow.com/a/24573266/4442731.
That way I can clear the applied search when the view is cancelled. This luckily also doesn't clear the view when the search is correctly entered! It's only called when the SearchView
properly leaves the view.
searchView.addOnAttachStateChangeListener(object: View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(p0: View?) {
// the view was expanded
}
override fun onViewDetachedFromWindow(p0: View?) {
// the view was collapsed
searchView.clearFocus()
DataManager.clearSearch()
}
})