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

Hel*_*oCW 1 android android-jetpack

在我看来,我应该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 
    }
Run Code Online (Sandbox Code Playgroud)

Sta*_*dar 11

binding.lifecycleOwner用于观察LiveData数据绑定。那种android:text=@{viewModel.text}地方val text:LiveData<String>。View 将在运行时观察文本变化。

  • @tsil 使用什么没有区别。如果“ViewDataBinding”没有“LifecycleOwner”,则所有视图更新只有在“invalidate()”之后才会被接受。 (4认同)