当前位置:网站首页>Usage of databinding
Usage of databinding
2022-04-23 08:08:00 【Mr_ Tony】
List of articles
One 、 Preface
DataBinding
yes JetPack
Part of , Generally speaking, if and JetPack
The effect will be better when used in combination with other parts of , Record it here . As mentioned before, if you want to refresh the data in real time when it changes UI It needs to use Observable
Subclasses of , such as ObservableInt
. Let's introduce if and LiveData
、ViewMode
Combined with refresh UI The situation of
Two 、LiveData Use
Here is a function , take LiveData
Is bound to UI above , Update the value after a period of time , Refresh it UI
class UserViewModel: ViewModel() {
val userName = MutableLiveData<String>(" The default value is ")
}
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 = " Update 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>
3、 ... and 、ViewMode Use
The following are from official documents
You can use the implementation
Observable
OfViewModel
Components , Send data change notification to other application components , This is with the use ofLiveData
Objects behave in a similar way .In some cases , You may prefer to implement
Observable
InterfaceViewModel
Components , Instead of usingLiveData
object , Even if this will lose the rightLiveData
The lifecycle management function of does not affect . Use to implementObservable
OfViewModel
Component allows you to better control the binding adapter in your application . for example , This pattern gives you better control over the notifications that are issued when data changes , You can also specify custom methods to set property values in bidirectional data binding .To achieve observable
ViewModel
Components , You must create one fromViewModel
Class inherits and implementsObservable
The class of the interface . You can useaddOnPropertyChangedCallback()
andremoveOnPropertyChangedCallback()
Method provides custom logic for observers to subscribe to or unsubscribe from notifications . You can alsonotifyPropertyChanged()
Method provides custom logic that runs when a property is changed . The following code example shows how to implement an observableViewModel
:
This method and custom implementation Observable
Classes are similar , Examples are as follows
ViewModel
class ObservableUserModel : ViewModel(), Observable {
private val callbacks: PropertyChangeRegistry = PropertyChangeRegistry()
@Bindable
var name = " The default value is "
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(" The new value --")
},1000)
}
}
Four 、 Reference link
版权声明
本文为[Mr_ Tony]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230643328685.html
边栏推荐
猜你喜欢
Buuctf misc brush questions
Research on software security based on NLP (2)
Sto with billing cross company inventory dump return
Thinkphp6 + JWT realizes login verification
云计算赛项--2020年赛题基础部分[任务3]
CTF攻防世界刷题51-
Upload labs range practice
CTF-MISC学习之从开始到放弃
Mobile terminal layout (3D conversion, animation)
[programming practice / embedded competition] learning record of embedded competition (I): establishment of TCP server and web interface
随机推荐
Attack and defense world misc questions 1-50
数据库之Mysql——概述安装篇
BUUCTF MISC刷題
php生成短链接:将数字转成字母,将字母转成数字
Ctf-misc summary
Intranet penetration series: dnscat2 of Intranet tunnel
几种智能机器人室内定位方法对比
Sto with billing cross company inventory dump return
分布式服务治理Nacos
nacos源码分析思路
Intranet penetration series: pingtunnel of Intranet tunnel
Research on system and software security (3)
[go]常见的并发模型[泛型版]
Go语学习笔记 - 数组 | 从零开始Go语言
Implementation of promise all
Link to some good tutorials or notes about network security and record them
Hierarchical output binary tree
Complete learning from scratch, machine learning and deep learning, including theory and code implementation, mainly using scikit and mxnet, and some practices (on kaggle)
upload-labs 靶场练习
php高精度计算