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 将在运行时观察文本变化。
| 归档时间: |
|
| 查看次数: |
2912 次 |
| 最近记录: |