View Binding is an Android library that allows you to easily access Views in your layouts using generated binding classes, rather than using findViewById() method. To use View Binding in Custom Views, you need to follow the below steps:
Add below code to your module level build.gradle file:
android {
...
viewBinding {
enabled = true
}
}
Create a new layout file for your custom view and add Views that you need to bind to. Add the root layout as MergeLayout
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click me"/>
</merge>
Create a new class for your custom view and inflate the layout using LayoutInflater
.
class CustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private lateinit var binding: CustomViewBinding
init {
initView(context)
}
private fun initView(context: Context) {
binding = CustomViewBinding.inflate(LayoutInflater.from(context), this, true)
}
}
You can access a view in the layout file through View Binding using the generated binding class. e.g. binding.textView.setText("Custom View")
.
class CustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private lateinit var binding: CustomViewBinding
init {
initView(context)
}
private fun initView(context: Context) {
binding = CustomViewBinding.inflate(LayoutInflater.from(context), this, true)
binding.textView.setText("Custom View")
}
}
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-05-21 04:36:13 +0000
Seen: 19 times
Last updated: May 21 '23
Can a transitive dependency in gradle be made exclusively for runtime purposes?
Why can't IntelliJ IDEA detect the Kotlin multiplatform library?
How do compileSdkVersion and targetSdkVersion differ from each other?
What does the error message "Failed to apply plugin [id 'com.jfrog.artifactory']" mean?
Why doesn't the Android Studio display the layout preview once MaterialCalendarView has been added?
How to update the outdated WebSecurityConfigurerAdapter in Spring Boot?
How can we add animation to the user interface using jetpack compose?