class SetContentView<in R : Activity, out T : ViewDataBinding>(
@LayoutRes private val layoutRes: Int) {
private var value : T? = null
operator fun getValue(thisRef: Activity, property: KProperty<*>): T {
value = value ?: DataBindingUtil.setContentView<T>(thisRef, layoutRes)
return value
}
}
val binding: ActivityDogBinding by contentView(R.layout.activity_dog)
DogActivity.kt
fun <R : Activity, T : ViewDataBinding> contentView(@LayoutRes layoutRes: Int):
SetContentView<R, T> {
return SetContentView(layoutRes)
}
当我尝试将活动称为
时val binding: ActivityLoginBinding by contentView(layoutRes = R.layout.activity_login)
抛出错误
Android Studio中的类型推断失败。请尝试明确指定类型参数:Kotlin
。我在IntelliJ中尝试过类似的工作。
答案 0 :(得分:2)
您需要为R
方法使用getValue
类型参数:
operator fun getValue(thisRef: R, property: KProperty<*>): T {
...
}