Since Kotlin Android Extensions, including Kotlin synthetics, is deprecated we forced to use View Binding. To find out how to Migrate from Kotlin synthetics to Jetpack view binding follow the link.
When you are done, you will find yourself with additional boilerplate code in each fragment. Inspired by this article Simple one-liner ViewBinding in Fragments and Activities with Kotlin I’ve created a little bit modified version of the fragment one-line view binding solution.
How to use it?
In each fragment just add this line and use the binding reference to get access to the views as you were using before that.
*The example below allows binding views from layout named fragment_home.xml.
class HomeFragment : Fragment(R.layout.fragment_home) {
private val binding by FragmentBinding(FrgmentHomeBinding::bind)
override fun onViewCreated(view: View, b: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.someTextViewId.text = "Yohoo"
}
}
FragmentBinding class code
class FragmentBinding<T : ViewBinding>(private val bindFunction: (View) -> T) :
ReadOnlyProperty<Fragment, T>, DefaultLifecycleObserver {
private var binding: T? = null
private var isObserving = false
// Should be called between onCreateView and onDestroyView
override fun getValue(thisRef: Fragment, property: KProperty<*>): T {
observeFragmentOnDestroy(thisRef)
if (binding != null) return binding as T
return bindFunction(thisRef.requireView()).also { binding = it }
}
private fun observeFragmentOnDestroy(fragment: Fragment) {
if (!isObserving) {
isObserving = true
fragment.viewLifecycleOwner.lifecycle.addObserver(this)
}
}
override fun onDestroy(owner: LifecycleOwner) {
binding = null
isObserving = false
owner.lifecycle.removeObserver(this)
}
}
More information about the deprecation and the reasons: Kotlin Android Extensions deprecation more detailed post
That’s it!