Skip to content

Instantly share code, notes, and snippets.

@afollestad
Last active March 2, 2022 21:02
Show Gist options
  • Select an option

  • Save afollestad/b9a8cd0468783d742b4ef2eb2a57819c to your computer and use it in GitHub Desktop.

Select an option

Save afollestad/b9a8cd0468783d742b4ef2eb2a57819c to your computer and use it in GitHub Desktop.
Some simple Kotlin view extensions
import android.view.View
import android.view.View.GONE
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.view.ViewTreeObserver
import android.widget.AdapterView
import android.widget.Spinner
fun View.show() {
visibility = VISIBLE
}
fun View.conceal() {
visibility = INVISIBLE
}
fun View.hide() {
visibility = GONE
}
fun View.enable() {
isEnabled = true
}
fun View.disable() {
isEnabled = false
}
fun View.showOrHide(show: Boolean) = if (show) show() else hide()
fun View.onLayout(cb: () -> Unit) {
if (this.viewTreeObserver.isAlive) {
this.viewTreeObserver.addOnGlobalLayoutListener(
object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
cb()
[email protected](this)
}
})
}
}
// Spinners
fun Spinner.onItemSelected(cb: (index: Int) -> Unit) {
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) = Unit
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) = cb(position)
}
}
// ScrollView
fun ScrollView.onScroll(cb: (y: Int) -> Unit) =
viewTreeObserver.addOnScrollChangedListener { cb(scrollY) }
// EditText
fun EditText.onTextChanged(
@IntRange(from = 0, to = 10000) debounce: Int = 0,
cb: (text: String) -> Unit
) {
addTextChangedListener(object : TextWatcher {
val callbackRunner = Runnable {
cb(text.trim().toString())
}
override fun afterTextChanged(s: Editable?) = Unit
override fun beforeTextChanged(
s: CharSequence,
start: Int,
count: Int,
after: Int
) = Unit
override fun onTextChanged(
s: CharSequence,
start: Int,
before: Int,
count: Int
) {
removeCallbacks(callbackRunner)
if (debounce == 0) {
callbackRunner.run()
} else {
postDelayed(callbackRunner, debounce.toLong())
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment