【问题标题】:Observing and binding object Android MVVM观察和绑定对象 Android MVVM
【发布时间】: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()}"

【问题讨论】:

标签: android kotlin mvvm


【解决方案1】:

你知道LiveData吗?,你可以使用Jetpack中包含的LiveData组件 这是为了观察差异层,例如 RepositoryViewModel 到其他层。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多