I\'m trying to follow data-binding example from official google doc https://developer.android.com/tools/data-binding/guide.html
except that I\'m trying to apply data
Everyone says about inflate()
, but what if we want to use it in onViewCreated()
?
You can use bind(view)
method of concrete binding class to get ViewDataBinding
instance for the view
.
Usually we write BaseFragment something like this (simplified):
// BaseFragment.kt
abstract fun layoutId(): Int
override fun onCreateView(inflater, container, savedInstanceState) =
inflater.inflate(layoutId(), container, false)
And use it in child fragment.
// ConcreteFragment.kt
override fun layoutId() = R.layout.fragment_concrete
override fun onViewCreated(view, savedInstanceState) {
val binding = FragmentConcreteBinding.bind(view)
// or
val binding = DataBindingUtil.bind(view)
}
If all Fragments uses data binding, you can even make it simpler using type parameter.
abstract class BaseFragment : Fragment() {
abstract fun onViewCreated(binding: B, savedInstanceState: Bundle?)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
onViewCreated(DataBindingUtil.bind(view)!!, savedInstanceState)
}
}
I don't know it's okay to assert non-null there, but.. you get the idea. If you want it to be nullable, you can do it.