一: 項目集成
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根節(jié)點按住option+enter(mac鍵位,win:Alt + Enter)
-
出現(xiàn)Convert to data binding layout 表示開啟成功
image.png
<?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:調(diào)整Activity初始化
ActivityMainBinding是Convert to data binding layout自動生成的類
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
// 調(diào)整后
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
//創(chuàng)建實體類
class MainViewModel {
var text1 = ""
var text2 = ""
}
//xml的data標(biāo)簽中添加變量
<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只能使用靜態(tài)方法
- @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:數(shù)組彬向、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]="數(shù)組1"
viewModel.map["good"] = "鍵值1"
}
btn2.setOnClickListener {
viewModel.list[0]="數(shù)組2"
viewModel.map["good"] = "鍵值2"
}
}
直接引用數(shù)組對象時兼贡,需要注意聲明的<>符號需要轉(zhuǎn)義
<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>
注意:若視圖復(fù)雜或動態(tài)計算長度導(dǎo)致顯示錯亂娃胆,重用異常遍希,可在onCreateViewHolder添加
binding.executePendingBindings()