简体   繁体   English

数据绑定 TextView 使用时无数据应用 function 分配 lifeCycleOwner

[英]Databinding TextView no data when use apply function to assign lifeCycleOwner

The TextView cannot display my data which fetch from network. TextView 无法显示我从网络获取的数据。 I am sure that I assign the lifecycleOwner and viewModel in onCreateView but nothing displayed.我确定我在 onCreateView 中分配了生命周期所有者和视图模型,但没有显示任何内容。 Then I remove apply function and assign lifecycleOwner line by line and it works but I don't know why.然后我删除 apply function 并逐行分配lifecycleOwner,它可以工作,但我不知道为什么。 Please tell me if anyone know the reason!请告诉我是否有人知道原因!

In ViewModel, I have a data class for display在 ViewModel 中,我有一个数据 class 用于显示

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

In Fragment, I assigned the lifecycleOwner and viewModel in onCreateView在 Fragment 中,我在 onCreateView 中分配了生命周期所有者和 viewModel

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然后我在 xml TextView 中使用 dataBinding 来观察 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}" />

You assign your binding.viewModel by binding.getViewModel().您通过 binding.getViewModel() 分配您的 binding.viewModel。 I think you want to assign the viewModel which init from fragment right?我想你想分配从片段中初始化的 viewModel 吗?

You should replace你应该更换

viewModel = viewModel

with

viewModel = this@YourFragment.viewModel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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