Is there a parent class for every binding class using View Binding?

2.4k views Asked by At

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?

2

There are 2 answers

0
SpiritCrusher On BEST ANSWER

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
}
0
Anh Huynh On

Works well for me !

typealias Inflate<T> = (LayoutInflater, ViewGroup?, Boolean) -> T

abstract class BaseFragment<VB : ViewBinding>(private val inflate: Inflate<VB>) : Fragment() {
    private var _binding: VB? = null
    val binding get() = _binding!!
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = inflate.invoke(inflater, container, false)
        return binding.root
    }
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}


class ChildFragment : BaseFragment<FragmentChildBinding>(FragmentChildBinding::inflate){
    
}