Last active
March 2, 2022 21:02
-
-
Save afollestad/b9a8cd0468783d742b4ef2eb2a57819c to your computer and use it in GitHub Desktop.
Some simple Kotlin view extensions
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
| 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