我正在尝试通过双向数据绑定实现ImageView颜色更改。我希望得到与编写 android:src =“#AAAAAA” 时相同的结果。
我的ViewModel:
class TeamsViewModel(application: Application) : BaseViewModel(application) {
val teamOneName: MutableLiveData<String> = MutableLiveData("Team One")
val teamOneColor: MutableLiveData<Int> = MutableLiveData()
val teamTwoName: MutableLiveData<String> = MutableLiveData("Team Two")
val teamTwoColor: MutableLiveData<Int> = MutableLiveData()
}
我的XML:
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/teamOneColorImageView"
android:layout_width="32dp"
android:layout_height="32dp"
android:src="@={viewModel.teamOneColor}" />
我确切不知道如何实现颜色更改。我尝试过:
object DataBindingAdapter {
@JvmStatic
@InverseBindingAdapter(attribute = "android:src")
fun ImageView.getColor(): Int {
val colorDrawable = this.drawable as ColorDrawable
return colorDrawable.color
}
@JvmStatic
@BindingAdapter("android:src")
fun ImageView.setColorx(color: Int?) {
val colorValue = color ?: Color.RED
val colorDrawable = ColorDrawable(colorValue)
this.setImageDrawable(colorDrawable)
}
}
但是我得到这个错误:
在视图类型'de.hdodenhof.circleimageview.CircleImageView'上找不到事件'android:srcAttrChanged'
接下来,我进行了研究,并尝试了这项研究:
object DataBindingAdapter {
@JvmStatic
@InverseBindingAdapter(attribute = "android:srcAttrChanged")
fun ImageView.getColorx(): Int {
val colorDrawable = this.drawable as ColorDrawable
return colorDrawable.color
}
@JvmStatic
@BindingAdapter("android:srcAttrChanged")
fun ImageView.setColor(color: Int?) {
val colorValue = color ?: Color.RED
val colorDrawable = ColorDrawable(colorValue)
this.setImageDrawable(colorDrawable)
}
@JvmStatic
@BindingConversion
fun convertColorToDrawable(color: Int): ColorDrawable? {
return if (color != 0) ColorDrawable(color) else null
}
@JvmStatic
@BindingConversion
fun convertDrawableToColor(drawable: Drawable): Int {
return (drawable as ColorDrawable).color
}
}
再次,错误:
无法找到用于接受参数类型'java.lang.Integer'的吸气剂。如果绑定适配器提供了吸气剂,请检查适配器的批注是否正确以及参数类型是否匹配。
您在类似方面有任何经验并想帮助我吗?