一: 项目集成
1:defaultConfig下开启databinding
defaultConfig {
applicationId "com.vecentek.demo"
minSdk 23
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
ndk {
abiFilters "arm64-v8a"
}
dataBinding{
enabled true //这里
}
}
2:xml文件测试
- 选中xml根节点按住option+enter(mac键位,win:Alt + Enter)
-
出现Convert to data binding layout 表示开启成功
<?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:tools="http://schemas.android.com/tools">
<data>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
3:调整Activity初始化
ActivityMainBinding是Convert to data binding layout自动生成的类
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
// 调整后
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding= ActivityMainBinding.inflate(LayoutInflater.from(this))
setContentView(binding.root)
}
}
4:试试效果
binding.apply {
textView1.text = "你好呀"
textView2.text = "很好很好"
}
5:加上viewModel
//创建实体类
class MainViewModel {
var text1 = ""
var text2 = ""
}
//xml的data标签中添加变量
<variable
name="vm"
type="com.example.databindingtest.MainViewModel" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{vm.text1,default=默认值1}"></TextView>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{vm.text2,default=默认值2}"
android:layout_marginTop="10dp"></TextView>
val viewModel = MainViewModel()
binding.apply {
vm = viewModel
viewModel.text1 = "测试1"
viewModel.text2 = "测试2"
}
- name为变量在xml中的对象名,自定义
- @{}表示引用变量值
- default 为默认展示值,仅xml中展示
6:改变viewmodel刷新UI
class MainViewModel {
var text1 = ObservableField<String>()
var text2 = ObservableField<String>()
}
val viewModel = MainViewModel()
binding.apply {
vm = viewModel
btn.setOnClickListener{
viewModel.text1.set("嘻嘻呀1")
viewModel.text2.set("嘻嘻呀2")
}
二:特殊用法
1:背景色使用变量
class MainViewModel {
var text1 = ObservableField<String>("哈哈")
var text1BackColor = ObservableInt(R.color.white)
var text1TextColor = ObservableInt(R.color.black)
}
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{vm.text1,default=默认值1}"
android:textColor="@{vm.text1TextColor}"
android:background="@{vm.text1BackColor}"></TextView>
点击两个按钮来回切换,白底黑字 黑底白字
binding.apply {
vm = viewModel
btn.setOnClickListener {
viewModel.text1BackColor.set(R.color.white)
viewModel.text1TextColor.set(ContextCompat.getColor(context,R.color.black))
}
btn2.setOnClickListener {
viewModel.text1BackColor.set(R.color.black)
viewModel.text1TextColor.set(ContextCompat.getColor(context,R.color.white))
}
}
object TextViewAdapter{
@JvmStatic
@BindingAdapter("android:background")
fun setBackground(view: TextView, colorResId: Int) {
view.setBackgroundResource(colorResId)
}
@JvmStatic
@BindingAdapter("android:textColor")
fun setTextColor(view: TextView, colorId: Int) {
view.setTextColor(colorId)
}
}
解释 object TextViewAdapter,这个类的声明表示为TextView添加适配器,在databinding解析到TextView的时候会去读该类的声明。
- @JvmStatic databinding只能使用静态方法
- @BindingAdapter("android:textColor") 绑定的属性
- set重写改属性的set方法
主要是databinding无法确定你绑定的值该做合种解析,需要自己指定。
注意:setBackgroundResource需要的是资源引用,setTextColor需要的资源id,传值之前需要确定
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt'
}
2:图片使用变量
原理同上, @BindingAdapter中不带android即app:imgUrl ,表示自定义属性
object ImageViewAdapter {
@JvmStatic
@BindingAdapter("android:src")
fun setSrc(imageView: ImageView, imgId: Int) {
imageView.setBackgroundResource(imgId)
}
@JvmStatic
@BindingAdapter("imgUrl")
fun setSrc(imageView: ImageView, imgUrl: String) {
Glide.with(imageView)
.load(url)
.into(imageView)
}
}
3:数组、Map
// Model中
var list = ObservableArrayList<String>()
var map = ObservableArrayMap<String, String>()
// xml中 引入使用的类
<data>
<variable
name="vm"
type="com.example.databindingtest.MainViewModel" />
<import type="java.util.ArrayList" />
<import type="java.util.Map"/>
</data>
<TextView android:text="@{vm.list.get(0)}"></TextView>
<TextView android:text="@{vm.map.get(`good`)}"></TextView>
// Activity中
viewModel.list.add("")
viewModel.list.add("")
viewModel.map["good"] = ""
binding.apply {
vm = viewModel
btn.setOnClickListener {
viewModel.list[0]="数组1"
viewModel.map["good"] = "键值1"
}
btn2.setOnClickListener {
viewModel.list[0]="数组2"
viewModel.map["good"] = "键值2"
}
}
直接引用数组对象时,需要注意声明的<>符号需要转义
<import type="xx.MainViewModel"></import>
<variable
name="vm"
type="MainViewModel" />
<import type="java.util.ArrayList" />
<variable
name="list"
type="ArrayList<MainViewModel>" />
4:事件绑定
在绑定的类中声明方法,以供使用
class Handlers{
fun bt3Click(view: View) {
Log.i("ABCD","我被点了")
}
}
<variable
name="handler"
type="xxx.Handlers" />
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="绑定事件"
android:onClick="@{handler::bt3Click}"/>
注意Activity中 binding.handler = Handlers()
5:显示隐藏
<import type="android.view.View"/>
android:visibility="@{vm.isShow?View.GONE:View.VISIBLE}"
6: RecyclerView
主要对adapter的使用
mRecyclerView.layoutManager = LinearLayoutManager(this@MainActivity)
val adapter = MyAdapter()
mRecyclerView.adapter = adapter
val model1 = ItemModel("yao","19")
val model2 = ItemModel("wang","18")
val model3 = ItemModel("li","1")
adapter.refresh(arrayListOf(model1,model2,model3))
class MyAdapter : RecyclerView.Adapter<MyRecyclerViewHolder>() {
var list = arrayListOf<ItemModel>()
fun refresh(data: ArrayList<ItemModel>) {
list = data
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyRecyclerViewHolder {
val binding = LayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MyRecyclerViewHolder(binding)
}
override fun onBindViewHolder(holder: MyRecyclerViewHolder, position: Int) {
holder.mBinding.vm = list[position]
}
override fun getItemCount(): Int {
return list.size
}
}
class MyRecyclerViewHolder(binding: LayoutBinding) : RecyclerView.ViewHolder(binding.root) {
var mBinding = binding
}
class ItemModel {
var name = ObservableField<String>()
var age = ObservableField<String>()
constructor(aName: String, aAge: String) {
name.set(aName)
age.set(aAge)
}
}
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="vm"
type="com.example.databindingtest.ItemModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/nameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{vm.name}"></TextView>
<TextView
android:id="@+id/ageText"
android:layout_marginLeft="100dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{vm.age}"></TextView>
</LinearLayout>
</layout>
注意:若视图复杂或动态计算长度导致显示错乱,重用异常,可在onCreateViewHolder添加
binding.executePendingBindings()