一、启用Databinding android { ? ? dataBinding { ? ? ? ? enabled = true ? ? } }
二、xml布局文件 <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 class=".LoginActivityBinding"> ? ? ? ? <!--需要的viewModel,通过mBinding.vm=mViewMode注入--> ? ? ? ? <variable ? ? ? ? ? ? name="model" ? ? ? ? ? ? type="com.cn21.hellokotlin.model.LoginModel" /> ? ? </data>
? ? <LinearLayout .../> ? ?? 界面加载: ?bind = DataBindingUtil.setContentView(this, R.layout.login_activity) ?bind!!.model = loginModel ? 三、数据Bean类 继承 BaseObservable 在get方法上加入@Bindable注解后,DataBinding就会在BR文件中生成相应的字段,BR是编译期间生成的类,类似于R文件。 属性值修改时,调用通知: notifyPropertyChanged(BR.name)
如果提示找不到BR类,作如下配置: apply plugin: "kotlin-kapt" kapt { ? ? generateStubs = true } //版本要与gradle版本一致 kapt ?"com.android.databinding:compiler:3.5.3"
四、数据变更时,会自动同步UI private fun doRandomTimer() { ? ? ? ? GlobalScope.launch { ? ? ? ? ? ? val random = Random() ? ? ? ? ? ? repeat(10){ ? ? ? ? ? ? ? ? delay(1000) ? ? ? ? ? ? ? ? bind?.model?.setName( "name_${random.nextInt(10)}" ) ? ? ? ? ? ? ? ? bind?.model?.setPhone( "${random.nextInt()}" ) ? ? ? ? ? ? } ? ? ? ? } ? ? } ? ?? 更新绑定语法: ? ?https://www.jianshu.com/p/e4c4a9aece40
五、ViewModel使用:
viewModel = ViewModelProviders.of(this).get(DubbyActivity2ViewModel::class.java)
会自动绑定到当前的Fragment或者Activity, 界面退出时会调用 viewModel.onCleard()
|