当前位置:网站首页>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
边栏推荐
- 云计算技能大赛 -- openstack私有云环境 第二部分
- Research on system and software security (3)
- 访问数据库的时候出现错误 Operation not allowed for a result set of type ResultSet.TYPE_FORWARD_ONLY.详解
- PHP high precision computing
- 3C装配中的机械臂运动规划
- Implementation of promise all
- Buuctf misc brush questions
- [programming practice / embedded competition] learning record of embedded competition (II): picture streaming based on TCP
- Positioning and decoration style
- Hump naming object
猜你喜欢

Ribbon start process

浏览器中的 Kubernetes 和 IDE | 交互式学习平台Killercoda

Intranet penetration series: dnscat2 of Intranet tunnel

Go语学习笔记 - Slice、Map | 从零开始Go语言

Mobile terminal layout (3D conversion, animation)

Attack and defense world misc questions 1-50

随笔(不定时更新)

【编程实践/嵌入式比赛】嵌入式比赛学习记录(二):基于TCP的图片流传输

Ctf-misc summary

攻防世界MISC刷题1-50
随机推荐
Hump naming object
Internal network security attack and defense: a practical guide to penetration testing (8): Authority maintenance analysis and defense
利用sqlmap注入获取网址管理员账号密码
KVM安装部署
Go语学习笔记 - 结构体 | 从零开始Go语言
数据安全问题已成隐患,看vivo如何让“用户数据”重新披甲
【编程实践/嵌入式比赛】嵌入式比赛学习记录(二):基于TCP的图片流传输
Cloud computing skills competition -- the first part of openstack private cloud environment
Principle of sentinel integrating Nacos to update data dynamically
Concours de compétences en informatique en nuage - - première partie de l'environnement cloud privé openstack
雲計算技能大賽 -- openstack私有雲環境 第一部分
浏览器中的 Kubernetes 和 IDE | 交互式学习平台Killercoda
Guoji Beisheng openstack container cloud environment construction
3C装配中的机械臂运动规划
Move layout (Flex layout, viewport label)
Research on system and software security (I)
Implementation principle of instanceof
GUI,CLI与Unix哲学
php生成短链接:将数字转成字母,将字母转成数字
Interview learning route