android - 为什么我可以绑定 String 或 LiveDataAndroid Studio 中的 android:text 变量?
问题描述
我正在学习数据绑定,以下代码来自项目。
plain_activity_solution_3.xmlandroid:text
中的绑定是_SimpleViewModel
name
String.
在solution.xml 中android:text
绑定到的是.SimpleViewModelSolution
name
LiveData<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}"
...
}
解决方案
正如文件所说:
任何普通对象都可用于数据绑定,但修改对象不会自动导致 UI 更新。数据绑定可用于使您的数据对象能够在其数据更改时通知其他对象(称为侦听器)。
LiveData<string>
也是可以观察到的。
推荐阅读
- facebook - Facebook AR Studio - 导入动画
- javascript - angular2 rxjs Observable - 提供的参数不符合调用目标的签名
- python - 我需要了解 Python for/while 语句的逻辑。蟒蛇 3.6
- sql - 如果单个查询中的列不为空,则动态连接列 - 对于大量列
- swift - 你可以装饰一个调试中断函数来中断调用该函数的位置吗?
- c# - CLR 函数不会返回超过 4000 个字符
- vb.net - 从 SQLite DB 读取在 vb.net 中失败
- c# - Active Directory:是否可以将项目添加到 SearchResultCollection
- sql - 我如何使用子查询来获取这里的总价?
- django - 我的登录视图一直说“使用此电子邮件的用户已经存在”。