Last active
June 24, 2021 09:30
-
-
Save rommansabbir/5f6f55ecd252d702d9c697d5bdd9a08f to your computer and use it in GitHub Desktop.
SearchView Extension Functions
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