当前位置:网站首页>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
ObservableOfViewModelComponents , Send data change notification to other application components , This is with the use ofLiveDataObjects behave in a similar way .In some cases , You may prefer to implement
ObservableInterfaceViewModelComponents , Instead of usingLiveDataobject , Even if this will lose the rightLiveDataThe lifecycle management function of does not affect . Use to implementObservableOfViewModelComponent 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
ViewModelComponents , You must create one fromViewModelClass inherits and implementsObservableThe 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
边栏推荐
猜你喜欢
随机推荐
Implementation principle of instanceof
Essays (updated from time to time)
惨了,搞坏了领导的机密文件,吐血分享备份文件的代码技巧
Jetson Xavier NX(3)Bazel Mediapipe 安装
thinkphp6+jwt 实现登录验证
Reading notes
strcat()、strcpy()、strcmp()、strlen()
Fibula dynamic programming
渗透测试面试合集---HVV---
Construction of middleman environment mitmproxy
【问题解决】VS2019解决编译生成的exe文件打不开的情况
攻防世界MISC刷题1-50
Go语学习笔记 - Slice、Map | 从零开始Go语言
A series of articles, a summary of common vulnerabilities of Web penetration (continuously updated)
Three minutes to teach you to use Houdini fluid > > to solve particle fluid droplets
Research on system and software security (I)
Research on system and software security (3)
3C裝配中的機械臂運動規劃
Thinkphp6 + JWT realizes login verification
分布式服务治理Nacos









