How To Implement Databinding With Reflection In Basefragment()
I'm trying to implement a BaseFragment in which I will pass the layout resource on it and it should outputs the binding to work in the fragment itself instead of need to do it ever
Solution 1:
I didn't hear about the possibility to get the databinding just from a layout, but even if it's possible, I don't think that is the recommended way, because of two reasons:
- Reflection is slow
 - It makes things more complicated than they are.
 
Instead of making magic with Reflection, you could do something like this:
abstractclassBaseFragment<out VB: ViewDataBinding>(
    privateval layout: Int,
    // Other Dependencies if wanted
) : Fragment() {
    abstractval viewModel: ViewModel
    // other variables that all fragments need// This does not cause any memory leak, because you are not storing the binding property.overridefunonCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = DataBindingUtil.inflate<VB>(inflater, layout, container, false).apply {
        lifecycleOwner = viewLifecycleOwner
        setVariable(BR.viewModel, viewModel)
    }.root
}
    overridefunonViewCreated(view: View, savedInstanceState: Bundle?) {
       // Do some basic work here that all fragments need// like a progressbar that all fragments share, or a button, toolbar etc.
    }
And then, when you still need the bindingProperty, I would suggest the following library (it handles all the onDestoryView stuff etc):
implementation 'com.kirich1409.viewbindingpropertydelegate:viewbindingpropertydelegate:1.2.2'You can then use this like:
classYourFragment(yourLayout: Int) : BaseFragment<YourBindingClass>() {
     privateval yourBinding: YourBindingClass by viewBinding()
     overrideval viewModel: YourViewModel by viewModels()
     overridefunonViewCreated(view: View, savedInstanceState: Bundle?) {
        // do binding stuff
     }
}
Let me know if this worked for you.
Cheers
Post a Comment for "How To Implement Databinding With Reflection In Basefragment()"