与Kotlin,BaseObservable和自定义委托的Android数据绑定

RBu*_*row 7 android observable kotlin android-databinding

我正在尝试编写一个自定义委托,它将清理Kotlin类中数据绑定的语法.它将消除为我可能想要观察的每个属性定义自定义getter和setter的需要.

Kotlin的标准实施如下:

class Foo : BaseObservable() {

    var bar: String
         @Bindable get() = bar
         set(value) {
             bar = value
             notifyPropertyChanged(BR.bar)
         }
}
Run Code Online (Sandbox Code Playgroud)

显然,有很多属性,这个类可以变得非常冗长.我想要的是把它抽象成一个像这样的委托:

class BaseObservableDelegate(val id: Int, private val observable: BaseObservable) {

     @Bindable
     operator fun getValue(thisRef: Any, property: KProperty<*>): Any {
         return thisRef
     }

     operator fun setValue(thisRef: Any, property: KProperty<*>, value: Any) {
         observable.notifyPropertyChanged(id)
     }
}
Run Code Online (Sandbox Code Playgroud)

然后,扩展BaseObservable的类可以返回到具有单行变量声明:

class Foo : BaseObservable() {
      var bar by BaseObservableDelegate(BR.bar, this)
}
Run Code Online (Sandbox Code Playgroud)

问题是如果没有Foo类中的@Bindable注释,BR中的bar就不会生成propertyId.我不知道用于生成该属性id的任何其他注释或方法.

任何指导将不胜感激.

eph*_*ent 14

您可以在不提供正文的情况下注释默认的getter或setter.

var bar: String by Delegates.observable("") { prop, old, new ->
    notifyPropertyChanged(BR.bar)
}
    @Bindable get
Run Code Online (Sandbox Code Playgroud)

有一个快捷方式注释用户站点目标,它做同样的事情.

@get:Bindable var bar: String by Delegates.observable("") { prop, old, new ->
    notifyPropertyChanged(BR.bar)
}
Run Code Online (Sandbox Code Playgroud)