【发布时间】:2020-07-20 18:42:02
【问题描述】:
如何从 View 中观察 ViewModel 中的对象? 例如。我有一个班级:
class MyClass {
var variable: Int = 0
fun increment() {
variable += 1
}
在视图模型中,我有一个此类的实例 - MyClassObject。 Fragment中有一个TextView,我想将它绑定到MyClassObject.variable
编辑。
我做了这样的事情并且它有效,但我认为这不是最好的方法。
class GameState
{
private val _variable = MutableLiveData<Int>()
val variable: LiveData<Int>
get() = _variable
init
{
_variable.value = 0
}
fun increment()
{
_variable.value = _variable.value!!.plus(1)
}
}
视图模型:
class GameViewModel : ViewModel()
{
private val _gameState: GameState = GameState()
val gameState: GameState
get() = _gameState
fun imgClick()
{
gameState.increment()
}
}
查看:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{gameViewModel.gameState.variable.toString()}" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{() -> gameViewModel.imgClick()}"
【问题讨论】:
-
参考这个链接:创建观察者类并将其与livedata一起使用stackoverflow.com/questions/48020377/…
-
提供更多代码