Skip to content Skip to sidebar Skip to footer

Android Viewbinding With Customview

I'd like to use try out the ViewBinding with custom view, for example: MainActivity <=> layout_main.xml MyCustomView <=> layout_my_custom_view.xml layout_main.xml <

Solution 1:

ViewDataBinding.inflate doesn't generate of child view accessor inside custom view.

thus, you can't touch line1(TextView) via only use ViewDataBinding.

If you don't want using findViewById or kotlin synthetic, MyCustomView also needs to apply ViewDataBinding. try as below.

CustomView

classMyCustomView@JvmOverloadsconstructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    privateval binding =
        CustomLayoutBinding.inflate(LayoutInflater.from(context), this, true)

    val line1
        get() = binding.line1

    val line2
        get() = binding.line2
}

MainActivity

overridefunonCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val binding = ActivityMainBinding.inflate(LayoutInflater.from(this))
    setContentView(binding.root)

    with(binding.customView) {
        line1.text = "Hello"
        line2.text = "World"
    }
}

Solution 2:

Another approach is to return the CustomView binding object.

classCustomViewconstructor(context: Context, attrs: AttributeSet?) : 
    ConstraintLayout(context, attrs){
                
        privateval _binding: CustomViewBinding = CustomViewBinding.inflate(
                        LayoutInflater.from(context), this, true)
                
                val binding get() = _binding    
        }

And then in your Activity or Fragment:

binding.customView.binding.line1?.text = "Hello"
binding.customView.binding.line2?.text = "World"

Solution 3:

Is it possible for you to share your MainActivity class?

How are you trying to reference views?

Ideally it should be possible for you to reference/access the views using either findViewById or Kotlin synthetic.

Solution 4:

I believe you can have setter in your custom view. Since ViewBinding generates binding class for your main layout, it should return you the CustomView class. Thus, you can use the setter you just wrote for changing the texts.

Post a Comment for "Android Viewbinding With Customview"