Search code examples
data-bindingandroid-databindingandroid-lifecycle

Databinding TextView no data when use apply function to assign lifeCycleOwner


The TextView cannot display my data which fetch from network. I am sure that I assign the lifecycleOwner and viewModel in onCreateView but nothing displayed. Then I remove apply function and assign lifecycleOwner line by line and it works but I don't know why. Please tell me if anyone know the reason!

In ViewModel, I have a data class for display

private val _priceData = MutableLiveData<PriceData>()
val priceData: LiveData<PriceData>
    get() = _priceData

In Fragment, I assigned the lifecycleOwner and viewModel in onCreateView

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    // The TextView display nothing using apply
    binding = FragmentPriceBinding.inflate(inflater, container, false).apply{
        lifecycleOwner = viewLifecycleOwner
        viewModel = viewModel
    }

    // The TextView show the data correctly if I assign lifeCycle line by line
    binding = FragmentPriceBinding.inflate(inflater, container, false)
    binding.lifecycleOwner = viewLifecycleOwner
    binding.viewModel = viewModel

    return binding.root
}

Then I use dataBinding in xml TextView to observe liveData

<data>
        <variable
            name="viewModel"
            type="com.yuyu.gasprice.price.PriceViewModel" />
</data>
<TextView
       android:id="@+id/gasoline_change"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:gravity="center"
       android:text="@{viewModel.priceData.predict}" />

Solution

  • You assign your binding.viewModel by binding.getViewModel() . I think you want to assign the viewModel which init from fragment right?

    You should replace

    viewModel = viewModel
    

    with

    viewModel = [email protected]