Ask Your Question
4

How does View Binding work in Custom Views?

asked 2023-05-21 04:36:13 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-21 04:41:02 +0000

woof gravatar image

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:

  1. Enable View Binding in your project

Add below code to your module level build.gradle file:

android {
    ...
    viewBinding {
        enabled = true
    }
}
  1. Create a new layout file for your custom view

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>
  1. Create a new Custom View class

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)
    }
}
  1. Access view through View Binding

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")
    }
}
edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-05-21 04:36:13 +0000

Seen: 18 times

Last updated: May 21 '23