Created
June 24, 2021 22:42
-
-
Save abircse/89ea3b294f3853dbf05315c366b32c7a to your computer and use it in GitHub Desktop.
Android Searchview Extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Add an action which will be invoked when the text is changing. | |
* | |
* @return the [SearchView.OnQueryTextListener] added to the [SearchView] | |
*/ | |
inline fun SearchView.doAfterTextChanged( | |
delay: Long = 500, | |
crossinline onTextChangedDelayed: (text: String) -> Unit | |
) = doOnQueryTextListener(delay, onTextChangedDelayed) | |
/** | |
* Add an action which will be invoked after the text changed. | |
* | |
* @return the [SearchView.OnQueryTextListener] added to the [SearchView] | |
*/ | |
inline fun SearchView.doOnQueryTextListener( | |
delay: Long, | |
crossinline onTextChangedDelayed: (text: String) -> Unit | |
): SearchView.OnQueryTextListener { | |
val queryListener = object : SearchView.OnQueryTextListener { | |
override fun onQueryTextSubmit(query: String?): Boolean = true | |
override fun onQueryTextChange(newText: String?): Boolean { | |
handlerPostDelayed(delay) { onTextChangedDelayed.invoke(newText ?: "") } | |
return true | |
} | |
} | |
this.setOnQueryTextListener(queryListener) | |
return queryListener | |
} | |
var handlerDelayTimer: Timer = Timer() | |
inline fun handlerPostDelayed(delay: Long, crossinline onSuccess: () -> Unit) { | |
handlerDelayTimer.cancel() | |
handlerDelayTimer = Timer() | |
handlerDelayTimer.schedule(object : TimerTask() { | |
override fun run() { | |
Handler(Looper.getMainLooper()).post { | |
onSuccess.invoke() | |
} | |
} | |
}, delay) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment