簡體   English   中英

數據綁定 TextView 使用時無數據應用 function 分配 lifeCycleOwner

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

TextView 無法顯示我從網絡獲取的數據。 我確定我在 onCreateView 中分配了生命周期所有者和視圖模型,但沒有顯示任何內容。 然后我刪除 apply function 並逐行分配lifecycleOwner,它可以工作,但我不知道為什么。 請告訴我是否有人知道原因!

在 ViewModel 中,我有一個數據 class 用於顯示

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

在 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
}

然后我在 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}" />

您通過 binding.getViewModel() 分配您的 binding.viewModel。 我想你想分配從片段中初始化的 viewModel 嗎?

你應該更換

viewModel = viewModel

viewModel = this@YourFragment.viewModel

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM