问题描述
我正在学习数据绑定,以下代码来自project。
plain_activity_solution_3.xml 中的android:text
通过SimpleViewModel
绑定到name
,String.
solution.xml 中的android:text
使用SimpleViewModelSolution
的{{1}}绑定到name
。
为什么LiveData<String>
或String
可以绑定到LiveData<string>
?在我看来,只能将一个绑定到android:text
。
SimpleViewModel.kt
android:text
plain_activity_solution_3.xml
class SimpleViewModel : ViewModel() {
val name = "Grace"
val lastName = "Hopper"
var likes = 0
private set // This is to prevent external modification of the variable.
...
}
SimpleViewModelSolution.kt
<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}"
...
}
solution.xml
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
...
}
解决方法
document说:
任何普通的旧对象都可以用于数据绑定,但是修改对象不会自动导致UI更新。数据绑定可用于使数据对象在数据发生更改时通知其他对象(称为侦听器)。
LiveData<string>
也可以观察到。
这是设计使然,在documentation中进行了讨论。绑定器将接受本机数据类型或“可观察”的内容,例如LiveData。如果提供了可观察对象,则绑定器将订阅对象的更改并将其更改绑定到视图,从而节省了代码行。