Answer the question
In order to leave comments, you need to log in
Why can't I use view binding in the child of the base fragment?
I made a basic snippet:
open class BaseFragment(val activity:Int) : Fragment() {
lateinit var mView: View
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mView=LayoutInflater.from(requireContext()).inflate(activity,container,false)
return mView
}
}
private lateinit var mBinding : FragmentAddBinding
Answer the question
In order to leave comments, you need to log in
//https://chetangupta.net/viewbinding/
abstract class ViewBindingFragment<VB : ViewBinding> : Fragment() {
private var _binding: ViewBinding? = null
abstract val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> VB
@Suppress("UNCHECKED_CAST")
protected val binding: VB
get() = _binding as VB
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = bindingInflater.invoke(inflater, container, false)
return requireNotNull(_binding).root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setup()
}
abstract fun setup()
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
class ProfileFragment :ViewBindingFragment<ProfileLayoutBinding>() {
override val bindingInflater: (LayoutInflater) -> ViewBinding
= ProfileLayoutBinding::inflate
override fun setup(){
//.. do stuff with binding variable
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question