I am using ViewBinding and I am trying to reduce the code creating a Fragment that is an abstract class and contains this code:
abstract class MyFragment<T> : Fragment() {
private var binding: T? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = getBinding()
return binding.root
}
abstract fun getBinding(): T
}
To make it work I need to make T extend a class and this class needs to be the parent of all the binding classes.
All the generated binding classes have a common parent? If that's the case what is it?
It should be ViewBinding
. The code snippet Should work for base fragment.
abstract class BaseFragment<V: ViewBinding> : Fragment(){
private var binding: V? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = getBinding()
return binding?.root
}
abstract fun getBinding(): V
}