Reputation: 24423
I'm using AndroidX library, my fragment is extend androidx.fragment.app.fragment.Fragment
, it provides a construction where I can simply give layout ID and skip overriding onCreateView
function like this:
class MyFragment (@LayoutRes layout:Int): Fragment(layout){
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//My View was created correctly.
}
}
Now how I can retrieve the binding object using DataBindingUtil?
I tried DataBindingUtil.getBinding(view) and DataBindingUtil.findBinding(view) but they always return null. Is there any way without overriding onCreateView
?
Upvotes: 1
Views: 107
Reputation: 24423
I just found the solution. it's more simple than I thought :|
class MyFragment (@LayoutRes layout:Int): Fragment(layout){
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
MyFragmentBinding.bind(view)?.let{
//Set binding data here.
}
}
}
read more here: https://zhuinden.medium.com/simple-one-liner-viewbinding-in-fragments-and-activities-with-kotlin-961430c6c07c
Upvotes: 2