1 | initial version |
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")
}
}