Android ViewModel 与 LiveData 的使用场景

发布时间: 2021-02-06 08:39:02 作者: 大象笔记

概述

使用逻辑

ViewModel 与 DataBinding 的关系

既然有了 ViewModel 的实现,为何还需要 DataBinding 呢?

实际上,ViewModel 诞生于 DataBinding 之后,是后出现的概念。

使用 DataBinding 结合 ViewModel 可以在 Layout XML 中写出跟微信小程序 WXML 一样的简洁描述。

参考:

https://developer.android.com/codelabs/android-databinding#2

// Bind the name property of the viewmodel to the text attribute
android:text="@{viewmodel.name}"
// Bind the nameVisible property of the viewmodel to the visibility attribute
android:visibility="@{viewmodel.nameVisible}"
// Call the onLike() method on the viewmodel when the View is clicked.
android:onClick="@{() -> viewmodel.onLike()}"

参考

我是一名山东烟台的开发者,联系作者