Created
January 9, 2024 03:28
-
-
Save nimaiwalsh/3614d655ab190145ce564963557e116a to your computer and use it in GitHub Desktop.
Android bind view extension function
This file contains 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
fun <T : View> Activity.bindView(viewId: Int) = | |
lazy { this.findViewById<T>(viewId) } |
This file contains 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
/** | |
* 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