【发布时间】:2019-11-12 06:34:11
【问题描述】:
我在Fragment 中静态地提供了一个绑定适配器,它基本上将我的按钮外观从“停止”更改为“播放”,反之亦然。
companion object {
@BindingAdapter("playState")
fun Button.setPlayState(item: UIState) {
item.let {
if (it.isPlaying) {
setText("Stop")
setBackgroundColor(ContextCompat.getColor(context, R.color.colorStop))
} else {
setText("Play")
setBackgroundColor(ContextCompat.getColor(context, R.color.colorPlay))
}
}
}
}
这是我的布局文件。我已经为它提供了一个数据类。
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<!-- stuff here -->
<variable
name="viewmodel"
type="com.mypackage.ui.ViewModel"/>
<variable
name="uistate"
type="com.mypackage.ui.UIState" />
</data>
<!-- layout, buttons, and more stuff here. Just pay attention to this following button -->
<Button
android:id="@+id/play_button"
android:layout_width="150sp"
android:layout_height="75sp"
android:layout_marginTop="20sp"
android:onClick="@{() -> viewmodel.onPlayClicked()}"
android:text="@string/play_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/minus_layout"
app:layout_constraintVertical_bias="0.026"
app:playState="@{uistate}"/>
</layout>
UIState 本身是不言自明的。
data class UIState(var isPlaying: Boolean)
() -> viewmodel.onPlayClicked() 在UIState 处翻转Boolean。
编译后,Data Binding Compiler 抛出此错误:
Cannot find a setter for <android.widget.Button app:playState>
that accepts parameter type 'com.mypackage.ui.UIState'
我试过了:
【问题讨论】:
标签: android kotlin android-databinding