Skip to content

Instantly share code, notes, and snippets.

@nimaiwalsh
Created January 9, 2024 03:28
Show Gist options
  • Save nimaiwalsh/3614d655ab190145ce564963557e116a to your computer and use it in GitHub Desktop.
Save nimaiwalsh/3614d655ab190145ce564963557e116a to your computer and use it in GitHub Desktop.
Android bind view extension function
fun <T : View> Activity.bindView(viewId: Int) =
lazy { this.findViewById<T>(viewId) }
/**
* Thanks to the lazy delegate, finding the view by id will be postponed until the property is used for the first time.
* This has some important optimisation improvements over the standard `lateinit` pattern usually used:
* 1. Property is read only
* 2. Initialization and definition can be kept together
* 3. Unused properties will be marked by IDE.
* 4. View reference that is never used will never be associated with the view element, and `findViewById` can be expensive.
* Excerpt From
* [Early Access] Advanced Kotlin
* Marcin Moskała
*/
class MainActivity : Activity() {
var questionLabelView: TextView by
bindView(R.id.main_question_label)
var answerLabelView: TextView by
bindView(R.id.main_answer_label)
var confirmButtonView: Button by
bindView(R.id.main_button_confirm)
override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment