Reputation: 321
mSearchView.setOnSearchClickListener {
// do something
}
This is being called when I click on the scrollView
's icon but if I write something in the searchbox and there is some text and after that click on the searchbox then this listener won't be called.
Update
mSearchView.setOnSearchClickListener {
scrollView.smoothScrollTo(0, 0)
}
I want to implement scroll to top behavior when the user clicks on the SearchView
. It works only the icon is visible but I don't know how to do it if the SearchView
is expanded.
Upvotes: 0
Views: 218
Reputation: 40830
Actually the first tap on the SearchView
is a click on the SearchView
itself; but once the SearchView
is expanded by a first tap (i.e the search icon is hidden), then next tap events are not detected by the SearchView
itself, but instead they are detected by its underlying AutoCompleteTextView
.
You can get access to the underling AutoCompleteTextView
of the SearchView
with below snippet, and then use its setOnClickListener
for doing the same code as you want in mSearchView.setOnSearchClickListener
val autoCompleteTextViewId =
mSearchView.context.resources
.getIdentifier("android:id/search_src_text", null, null)
val searchAutoCompleteTextView =
mSearchView.findViewById<AutoCompleteTextView>(autoCompleteTextViewID)
searchAutoCompleteTextView.setOnClickListener {
// Do the same as you want to do as in `mSearchView.setOnSearchClickListener`
scrollView.smoothScrollTo(0, 0)
}
Upvotes: 2
Reputation: 321
I can solve my problem using Zain idea and an example from another post: https://stackoverflow.com/a/65175943/13091576
I also had to write an onFocusChangeListener, because setOnClickListener only triggers when the AutoCompleteTextView has focus.
val autoCompleteTextViewId = mSearchView.context.resources.
getIdentifier("android:id/search_src_text", null, null)
val searchAutoCompleteTextView =
mSearchView.findViewById<AutoCompleteTextView>(autoCompleteTextViewId)
searchAutoCompleteTextView?.setOnClickListener {
memoriesScrollView.smoothScrollTo(0, 0)
}
searchAutoCompleteTextView?.setOnFocusChangeListener { v, hasFocus ->
if(hasFocus) {
memoriesScrollView.smoothScrollTo(0, 0)
}
}
Upvotes: 2