Create CustomView with ViewBinding

Vinh Bui
2 min readMar 17, 2021

--

Kotlin Android Extensions is deprecated, which means that using Kotlin synthetics for view binding is no longer supported. If your app uses Kotlin synthetics for view binding, use this guide to migrate to Jetpack view binding.

Easily migrate from Kotlin Android Extensions to View Binding, see here

https://developer.android.com/topic/libraries/view-binding

But the only sample for Activity and Fragment, and now I write this tutorial for how to apply View Binding to CustomView

The first step, open build.gradle and add

android {
...
buildFeatures {
viewBinding true
}
}

Second, create your layout view_custom.xml, for Example, I add TextView and Button on the layout

Next, create ViewCustom.kt class

You can see it in ViewCustom.kt, ViewBinding can use by

private val binding = ViewCustomBinding.inflate(LayoutInflater.from(context), this, true)

Let’s add CustomView on your UI

I don’t rewrite how to use ViewBinding on Activity, you can read on the Android developer page, now see MainActivity.kt

I split click on CustomView and click on the child of Customview (Button), the solution is to create another callback for child click, like:

private var callback: CustomViewCallback? = nullfun onClick(listener: CustomViewCallback) {
callback = listener
}

And add callback here:

binding.tvAdd.setOnClickListener {
callback?.onClick(binding.tvValue.text.toString())
}

Tips:

If on your project use Parcelable, when removing plugin’Kotlin-android-extention’, can’t import Parcelize because “Kotlin-android-extention” includes Parcelize plugin.

Unresolved reference: Parcelize

To solve it, open build.gradle and add ‘kotlin-parcelize’ plugin

plugins {
...
id 'kotlin-parcelize'
}

Let run the project and see the screenshot:

You can download the source code here

And that’s all. If you liked this article, don’t forget to support me by clapping

--

--