开启dataBinding
app build.gradle
android {
buildFeatures {
dataBinding true
}
}
-
一些依赖库
def lifecycle_version = "2.4.1" // https://developer.android.google.cn/jetpack/androidx/releases/lifecycle?hl=en // LiveData api "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version" // ViewModel api "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version" // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process api "androidx.lifecycle:lifecycle-process:$lifecycle_version" // Lifecycles only (without ViewModel or LiveData) api "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version" // 在Activity中使用viewModels api "androidx.activity:activity-ktx:1.3.1" // 在Fragment中使用viewModels api "androidx.fragment:fragment-ktx:1.3.6"
基类
abstract class BaseActivity<VDB : ViewDataBinding>(private var contentViewID:Int){
protected lateinit var binding: VDB
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, contentViewID)
}
}
子类
class MainActivity : BaseActivity<ActivityMainBinding>(R.layout.activity_main){
private val xVM: XxxxVM by viewModels()
// 发起任务
xVM.getXx(xId)
// 处理结果
xVM.xLiveData.observe(this) { bid ->
}
}
xml布局
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<include
android:id="@+id/tabLayout"
layout="@layout/tab_main_activity" />
</LinearLayout>
</layout>
处理任务的ViewMode
class BindBrandVM : ViewModel() {
val xLiveData = MutableLiveData<String>()
fun getXx(x: String) {
RetrofitManager.api.xxxxx(FormBody.Builder()
.add("xxx", x)
.build())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : BaseSubscriber<BaseHttpEntity<XxxxRes>>() {
override fun onErr(throwable: Throwable) {}
override fun onNext(res: BaseHttpEntity<XxxxRes>) {
super.onNext(res)
try {
if (res.result != null) {
val bid = res.result!!.bid
xLiveData.value = bid
}
} catch (e: java.lang.Exception) {
}
}
})
}
}
还可以添加其他jetpack库。。。。。。。。。。。