How to use data-binding with Fragment

后端 未结 14 1041
不思量自难忘°
不思量自难忘° 2020-11-29 16:48

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

14条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 17:09

    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.

提交回复
热议问题