When DataBinding performs data binding, after the data is updated, the page content does not refresh, and 80% of them do not trigger the ui refresh

When I first entered databinding, I encountered such a problem. When I used kotlin's data class to write data classes and realized two-way binding, the data was updated successfully, but the TextView of the page was not refreshed. After researching, the page was not updated, name There are two options for updating

Method 1 (not recommended) : Execute invalidateAll() every time new data is assigned. This method is not recommended, because it is too troublesome to call every update, and this method is to update all content, which is not very beautiful. .

binding.invalidateAll()

Method 2 (recommended): When defining a data class, it needs to be set as an observable data class, that is, inherit BaseObervable, and add @Bindable annotation to the property bound to ui, and then execute it in the set(value) method notifyPropertyChanged(BR.studyType) to refresh the data on the page. The BR class here is also automatically generated. This method is to observe the modified properties and refresh a single property. This method is really wonderful.


class HomeData: BaseObservable() {
    @Bindable
    var studyType: StudyType = StudyType(1,"任务")
    set(value) {
        field = value
        notifyPropertyChanged(BR.studyType)
    }
    val studyTypeList: MutableList<StudyType> = mutableListOf(StudyType(1,"任务"),
        StudyType(2,"情绪"),StudyType(3,"经验"),StudyType(4,"目标"))
    data class StudyType(
        var id: Int,
        var name:String
    )
}

Note: If the annotation @Bindable is red, you need to add the id 'kotlin-kapt' to the build.gradle under the app

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-kapt'
}

Guess you like

Origin blog.csdn.net/Spy003/article/details/128945879