首页 > 解决方案 > 为什么我可以绑定 String 或 LiveDataAndroid Studio 中的 android:text 变量?

问题描述

我正在学习数据绑定,以下代码来自项目

plain_activity_solution_3.xmlandroid:text中的绑定是_SimpleViewModelnameString.

solution.xml 中android:text绑定到的是.SimpleViewModelSolutionnameLiveData<String>

为什么可以String或被LiveData<string>绑定到android:text?在我看来,只允许绑定一个 android:text

简单视图模型.kt

class SimpleViewModel : ViewModel() {
    val name = "Grace"
    val lastName = "Hopper"
    var likes = 0
        private set // This is to prevent external modification of the variable.
    ...
}

plain_activity_solution_3.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="viewmodel"
            type="com.example.android.databinding.basicsample.data.SimpleViewModel"/>
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/plain_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="128dp"
            android:text="@{viewmodel.name}"
    ...
}

SimpleViewModelSolution.kt

class SimpleViewModelSolution : ViewModel() {
    private val _name = MutableLiveData("Ada")
    private val _lastName = MutableLiveData("Lovelace")
    private val _likes =  MutableLiveData(0)

    val name: LiveData<String> = _name
    val lastName: LiveData<String> = _lastName
    val likes: LiveData<Int> = _likes
    ...
}

解决方案.xml

<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="viewmodel"
            type="com.example.android.databinding.basicsample.data.SimpleViewModelSolution"/>
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- A simple binding between a TextView and a string observable in the ViewModel -->
        <TextView
            android:id="@+id/name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="128dp"
            android:text="@{viewmodel.name}"
...
}

标签: androidandroid-livedata

解决方案


正如文件所说:

任何普通对象都可用于数据绑定,但修改对象不会自动导致 UI 更新。数据绑定可用于使您的数据对象能够在其数据更改时通知其他对象(称为侦听器)。

LiveData<string>也是可以观察到的。


推荐阅读