为什么我不能对 TextView textColor 使用数据绑定?

Why I can't use databinding for TextView textColor?

我有 TextView 和 当我绑定 android:textColor="@{viewModel.theme.primaryTextColor}" 其中 primaryTextColor 是数据 class Theme(val primaryTextColor:String)

我遇到了这个编译错误 Cannot find a setter for \u003candroid.widget.TextView android:textColor\u003e that accepts parameter type \u0027java.lang.String\u0027\n\nIf a binding adapter provides the setter, check that the adapter is annotated correctly and that the parameter type matches."

只要我一改 android:textColor ="#FF00000" 就可以了

试试这个

@BindingAdapter({"bind:color"})
fun setColor(textView : TextView , primaryTextColor :String ) {
    textView.textColor = (ContextCompat.getColor(textView.getContext(), primaryTextColor)
}

并在 xml 中添加此行

app:color="@{viewModel.theme.primaryTextColor}"

注意:primaryTextColor 是字符串,如果没有相应地改变。