1

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?

  • Does this answer your question? [How using ViewBinding with an abstract base class](https://stackoverflow.com/questions/62407823/how-using-viewbinding-with-an-abstract-base-class) – Chetan Gupta Dec 06 '20 at 10:33

1 Answers1

6

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
}
ADM
  • 20,406
  • 11
  • 52
  • 83