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

Mustafa Yiğit
ProAndroidDev
Published in
2 min readDec 5, 2020

--

viewBinding

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 ViewBinding to our project.

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 ViewBinding 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 ViewBinding in Activity:

private lateinit var mBinding: ActivityMainBindingoverride fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mBinding.root)
with(mBinding){
btnRefresh.setOnClickListener {}
}
}

Use ViewBinding 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
super.onDestroy()
}

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

Like:

// 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) {
with(binding){
btnItemSelection.text = item
}
}
}
// Adapter - onCreateViewHolder
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewBindingExampleHolder(
// Inflate generated item binding class
AdapterItemViewBindingExampleBinding.inflate(
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 :)

--

--