1.在app的build.gradle文件里开启配置:
android {
...
buildFeatures {
dataBinding true
}
}
2.布局代码:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="student"
type="com.example.myapplication.data.Student" />
<variable
name="like"
type="com.example.myapplication.data.Like" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/tv_my"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:text="@{(student.like.likeName == null) ? student.name : student.like.likeName}"
android:layout_width="200dp"
android:layout_height="100dp"
android:background="@color/purple_200"/>
<Button
android:id="@+id/btn_my"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/tv_my"
app:layout_constraintStart_toStartOf="@id/tv_my"
android:text="show"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
3.相关实体类:
package com.example.myapplication.data
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import com.example.myapplication.BR
class Student{
var name:String? = "name"
var like:Like? = null
}
class Like {
var likeName:String? = null
}
4.Activity的使用代码:
class MainActivity : AppCompatActivity() {
private lateinit var recycler: RecyclerView
private lateinit var ctb: CollapsingToolbarLayout
private lateinit var appBarLayout: AppBarLayout
private lateinit var mToolbar:Toolbar
private var student:Student ?= null
lateinit var binding:ActivityMain4Binding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMain4Binding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnMy.setOnClickListener {
student?.like = Like().apply {
likeName = "likename"
}
student?.name = "name2"
}
student = Student().apply {
name = "name"
}
testBinding()
}
private fun testBinding(){
binding.student = this.student
}
但是这个时候我们会发现,只有第一次新建的时候,起作用,我们点击按钮的时候是没反应的。所以我们要实现BaseObervable。
class Student : BaseObservable(){
@get:Bindable
var name:String? = "name"
set(value) {
field = value
notifyPropertyChanged(BR.name)
}
@get:Bindable
var like:Like? = null
set(value) {
field = value
notifyPropertyChanged(BR.like)
}
}
这个时候就可以动态更改xml里的数据了。我们来看下界面:
这个时候我们点击按钮:
it works!