Kişisel web sayfamda yazılım, teknoloji ve genel hayat hakkında paylaşımlar yapmayı hedefliyorum.

Kotlin Synthetic is Dead, Long Live ViewBinding (Kotlin Android Extensions Deprecated)

view binding

Recently, Jetbrains team released a new update for Kotlin. (Kotlin 1.4.20 Released) With this update, synthetic import has been removed from use. And now ViewBinding is recommended as an alternative. Let’s see how we can add to our project. (Or you can use DataBinding)

First of all, we must tell gradle that we will use viewBinding.

Note that ViewBinding works at module level. If our project has more than one module, we need to enable in each module we will use.

android {
    buildFeatures {
        viewBinding true

Now this code block will be generate Binding Class for each layout file in our project. We must inflate this Binding Classes for using.

activity_main.xml → ActivityMainBinding

Use in Activity:

private lateinit var mBinding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
    mBinding = ActivityMainBinding.inflate(layoutInflater)
        btnRefresh.setOnClickListener {}

Use in Fragment:

private var mBinding: FragmentHomeBinding? = null
override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
mBinding = FragmentHomeBinding.inflate(layoutInflater, container, false)
    return mBinding!!.root
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    with(mBinding) {
        btnDismiss.setOnClickListener{ }
override fun onDestroy() {
    mBinding = null

If the layout has already been inflated, we can instead call the binding class’s bind(view: View) method.


// HomeFragment.kt
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val mBinding = FragmentHomeBinding.bind(view)
    with(mBinding) {
        // now it's ready

So how do we use it in the adapter?

// ViewHolder
class ViewBindingExampleHolder(
    private val binding: AdapterItemViewBindingExampleBinding
) : RecyclerView.ViewHolder(binding.root) {
    fun bind(item: String) {
            btnItemSelection.text = item
// Adapter - onCreateViewHolder
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewBindingExampleHolder(
    // Inflate generated item binding class
        LayoutInflater.from(parent.context), parent, false

And that’s all. If you liked thi article, don’t forget to support me by clapping and if you have any questions, write to me 🙂

Github Android Examples



You may also like...

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir