data binding library (一)
data binding 双向绑定
- 使用 BaseObservable 类 , @Bindable注解 和 notifyPropertyChanged()方法的使用
- 使用 ObservableFields 定义final属性
- 使用 ObservableMap
- 使用 ObservableArrayList
//model 这里使用的Kotlin语法,不懂的可以匹配成java的看
class TestActivityForm : BaseObservable() {
//BaseObservable
@Bindable
var address: String = ""
set(value) {
field = value
notifyPropertyChanged(BR.address)
}
//ObservableFields
val userName = ObservableField<String>()
val password = ObservableField<String>()
val name = ObservableField<String>()
val mobile = ObservableField<String>()
}
}
//view 布局
<data>
//ObservableMap
<import type="android.databinding.ObservableMap" />
<variable
name="mapTestData"
type="ObservableMap<String, Object>"/>
//ObservableArrayList
<import type="android.databinding.ObservableList"/>
<variable name="listTestData" type="ObservableList<Object>"/>
//ObservableFields, BaseObservable
<variable
name="testInfo"
type="com.xwjr.wwxh_login.model.form.TestActivityForm" />
<variable
name="acitivity"
type="com.xwjr.wwxh_login.activity.TestActivity" />
</data>
//调用方式
android:text="@={testInfo.userName}" //ObservableFields, BaseObservable
android:text="@={mapTestData[`age`]}" //ObservableMap
android:text="@{listTestData[1]}" //ObservableArrayList
//activity调用
private val testActivityForm = TestActivityForm()
private val mapTestData = ObservableArrayMap<String, Any>()
private val listTestData = ObservableArrayList<Any>()
activityMainBinding.testInfo = testActivityForm
activityMainBinding.acitivity = this
activityMainBinding.mapTestData = mapTestData
activityMainBinding.listTestData = listTestData