简体   繁体   中英

How to use DataBinding with AndroidX fragment

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM