gpt4 book ai didi

android - 我应该在使用 viewModel 时添加 binding.lifecycleOwner=this 吗?

转载 作者:行者123 更新时间:2023-12-04 23:45:49 25 4
gpt4 key购买 nike

在我看来,我应该添加 binding.lifecycleOwner=this当我使用 viewModel .
我发现很多项目,例如 Code A 没有添加 binding.lifecycleOwner=this , 为什么?
代码 A 来自项目 https://github.com/enpassio/Databinding
代码 A

class AddToyFragment : androidx.fragment.app.Fragment() {

private lateinit var binding: AddToyBinding
...

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(
inflater, R.layout.fragment_add_toy, container, false
)

setHasOptionsMenu(true)

return binding.root
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
(requireActivity() as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true)

//If there is no id specified in the arguments, then it should be a new toy
val chosenToy : ToyEntry? = arguments?.getParcelable(CHOSEN_TOY)

//Get the view model instance and pass it to the binding implementation
val factory = AddToyViewModelFactory(provideRepository(requireContext()), chosenToy)
mViewModel = ViewModelProviders.of(this, factory).get(AddToyViewModel::class.java)

binding.viewModel = mViewModel

binding.fab.setOnClickListener {
saveToy()
}

binding.lifecycleOwner=this //I think it should add
}

最佳答案

binding.lifecycleOwner用于观察LiveData与数据绑定(bind)。
种类android:text=@{viewModel.text}在哪里 val text:LiveData<String> . View 将在运行时观察文本变化。

关于android - 我应该在使用 viewModel 时添加 binding.lifecycleOwner=this 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62591052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com