Android使用LiveData替换ObservableField做Data Binding
Android Studio 3.1 Canary 6 开始支持使用LiveData做Data Binding。
这里简单介绍下使用LiveData替换ObservableField做Data Binding(开发语言为kotlin)。
环境准备
1、安装Android Studio 3.1 Canary 6或以上版本。
2、升级Android Gradle插件
buildscript {
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0-alpha06'
    }
}
3、更新databinding编译器的版本
kapt 'com.android.databinding:compiler:3.1.0-alpha06'
app的build.gradle如下:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.livedatabinding"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled = true
    }
}
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'android.arch.lifecycle:extensions:1.0.0'
    kapt 'com.android.databinding:compiler:3.1.0-alpha06'
    kapt 'android.arch.lifecycle:compiler:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
使用
原来使用ObserverableField的ViewModel
class UsersViewModel : ViewModel() {
    private val userRepository = UserRepository()
    val name = ObservableField<String>()
    val age = ObservableInt()
    init {
        userRepository.addUser{
            name.set(it.name)
            age.set(it.age)
        }
    }
}
改用LiveData
class UserViewModel : ViewModel() {
    private val userRepository = UserRepository()
    val name = MutableLiveData<String>()
    val age = MutableLiveData<Int>()
    init {
        userRepository.updateUserInfo{
            name.postValue(it.name)
            age.postValue(it.age)
        }
    }
}
注意:LiveData暴露公开两个方法用于设置值
- postValue:允许后台线程向主进程推送数据
- setValue:只允许在主线程调用,如果在其他线程调用会报错:This method must be called from the main thread
绑定LiveData并对Binding设置LifecycleOwer:
class UserActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: ActivityUserBinding? = setContentView(this, R.layout.activity_user)
        val viewModel = ViewModelProviders.of(this).get(UserViewModel::class.java)
        binding?.let {
            it.viewModel = viewModel
            it.setLifecycleOwner(this)
        }
    }
}
由于Live Data会遵从其他应用组件(如activity,fragment)的生命周期,它只会在UI组件处在active状态(如activity处在started和resumed )时才会推送数据。这样避免了我们UI展示数据时,需要检查下组件是否存在。
 
             
             
             
             
            