当前位置:网站首页>DataBinding的使用五
DataBinding的使用五
2022-04-23 06:43:00 【Mr_Tony】
一、前言
DataBinding是JetPack的一部分,通常来说如果和JetPack的其它部分结合使用效果会更好,这里对其进行记录。之前说过如果想要使数据改变的时候实时刷新到UI上面需要使用Observable的子类才行,比如ObservableInt。这里介绍一下如果和LiveData、ViewMode结合使用刷新UI的情况
二、LiveData的使用
这里实现一个功能,将LiveData的数据绑定到UI上面,隔一段时间后更新该值,使其刷新UI
class UserViewModel: ViewModel() {
val userName = MutableLiveData<String>("默认值")
}
class MainActivity : AppCompatActivity() {
private val binding: ActivityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val viewModel = ViewModelProvider(this).get(UserViewModel::class.java)
binding.viewmodel = viewModel
binding.lifecycleOwner = this
binding.root.postDelayed({
viewModel.userName.value = "更新值"
},1000)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:bind="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools">
<data>
<variable name="viewmodel" type="com.example.myapplication.UserViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">
<TextView android:id="@+id/update_content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="@{viewmodel.userName}" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent" tools:text="value" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
三、ViewMode的使用
以下源自官方文档
您可以使用实现
Observable的ViewModel组件,向其他应用组件发出数据变化通知,这与使用LiveData对象的方式类似。在某些情况下,您可能更愿意使用实现
Observable接口的ViewModel组件,而不是使用LiveData对象,即使这样会失去对LiveData的生命周期管理功能也不影响。使用实现Observable的ViewModel组件可让您更好地控制应用中的绑定适配器。例如,这种模式可让您更好地控制数据更改时发出的通知,您还可以指定自定义方法来设置双向数据绑定中的属性值。如需实现可观察的
ViewModel组件,您必须创建一个从ViewModel类继承而来并实现Observable接口的类。您可以使用addOnPropertyChangedCallback()和removeOnPropertyChangedCallback()方法提供观察器订阅或取消订阅通知时的自定义逻辑。您还可以在notifyPropertyChanged()方法中提供属性更改时运行的自定义逻辑。以下代码示例展示了如何实现一个可观察的ViewModel:
该方式和自定义实现Observable类的方式差不多,示例如下
ViewModel
class ObservableUserModel : ViewModel(), Observable {
private val callbacks: PropertyChangeRegistry = PropertyChangeRegistry()
@Bindable
var name = "默认值"
fun updateName(newName : String){
name = newName
notifyPropertyChanged(BR.name)
}
override fun addOnPropertyChangedCallback(
callback: Observable.OnPropertyChangedCallback) {
callbacks.add(callback)
}
override fun removeOnPropertyChangedCallback(
callback: Observable.OnPropertyChangedCallback) {
callbacks.remove(callback)
}
/** * Notifies observers that all properties of this instance have changed. */
fun notifyChange() {
callbacks.notifyCallbacks(this, 0, null)
}
/** * Notifies observers that a specific property has changed. The getter for the * property that changes should be marked with the @Bindable annotation to * generate a field in the BR class to be used as the fieldId parameter. * * @param fieldId The generated BR id for the Bindable field. */
fun notifyPropertyChanged(fieldId: Int) {
callbacks.notifyCallbacks(this, fieldId, null)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:bind="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools">
<data>
<variable name="observableModel" type="com.example.myapplication.ObservableUserModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">
<TextView android:id="@+id/update_content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="@{observableModel.name}" android:paddingStart="10dp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent" tools:text="value" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val binding: ActivityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
// Obtain ViewModel from ViewModelProviders
val viewModel = ViewModelProvider(this).get(ObservableUserModel::class.java)
binding.observableModel = viewModel
binding.root.postDelayed({
viewModel.updateName("新值--")
},1000)
}
}
四、参考链接
版权声明
本文为[Mr_Tony]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Mr_Tony/article/details/124326069
边栏推荐
- Research on system and software security (4)
- Ctf-misc learning from start to give up
- Complete color conversion formulas and conversion tables (31 kinds)
- Sto with billing cross company inventory dump return
- Chapter V investment real estate
- 爬虫学习笔记,学习爬虫,看本篇就够了
- Using lambda expression to solve the problem of C file name sorting (whether it is 100 or 11)
- Internal network security attack and defense: a practical guide to penetration testing (VII): cross domain attack analysis and defense
- feign如何集成hystrix
- Go语学习笔记 - Slice、Map | 从零开始Go语言
猜你喜欢
![BUUCTF [极客大挑战 2019]EasySQL1](/img/ad/afca09bc1da003393319af700e90e3.png)
BUUCTF [极客大挑战 2019]EasySQL1

Go语学习笔记 - 语言接口 | 从零开始Go语言

DVWA靶场练习

Go语学习笔记 - 结构体 | 从零开始Go语言

SAP GUI security

攻防世界MISC刷题1-50

Mysql database backup and recovery under Linux (full + incremental)

SAP tr manual import system operation manual

Chapter V investment real estate

FUEL: Fast UAV Exploration using Incremental Frontier Structure and Hierarchical Planning
随机推荐
Move layout (Flex layout, viewport label)
Ctf-misc learning from start to give up
【编程实践/嵌入式比赛】嵌入式比赛学习记录(二):基于TCP的图片流传输
Flutter之Provider共享数据的两种方式
Chapter VII asset impairment
Analysis of Nacos source code
内网渗透系列:内网隧道之icmp_tran
Redis transaction implements optimistic locking principle
攻防世界MISC刷题1-50
云计算技能大赛 -- openstack私有云环境 第二部分
SAP GUI security
数据库之MySQL——基本常用查询命令
SAP self created table log function is enabled
Asynchronous learning
国基北盛-openstack-容器云-环境搭建
Sto with billing cross company inventory dump return
Chapter V investment real estate
Internal network security attack and defense: a practical guide to penetration testing (IV): Authority improvement analysis and defense
Complete learning from scratch, machine learning and deep learning, including theory and code implementation, mainly using scikit and mxnet, and some practices (on kaggle)
GUI,CLI与Unix哲学