我想在xml中使用databinding与颜色变量,以下是我的代码。
xml:
<data>
<import type="androidx.core.content.ContextCompat"/>
<variable
name="settings"
type="..censored..Settings" />
</data>
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:textColor="@{ContextCompat.getColor(context, settings.primaryTextColor)}"
android:textColorHint="@{ContextCompat.getColor(context, settings.primaryHintColor)}"
/>
设置。
data class Settings(val context: Context) {
var primaryTextColor: Int
var primaryHintColor: Int
init {
primaryTextColor = R.color.defaultText
primaryHintColor = R.color.defaultHint
}
然而,我得到一个错误
找不到一个接受参数类型为'int'的setter。
如何实现用变量对颜色进行数据化绑定?
你可以使用 BindingAdapter
为此。
@BindingAdapter("textColor")
fun bindTextColor(textInputEditText: TextInputEditText, textColorResource: Int?) {
if (textColorResource != null) {
textInputEditText.setTextColor(ContextCompat.getColor(textInputEditText.context, textColorResource))
}
}
@BindingAdapter("textColorHint")
fun bindTextColor(textInputEditText: TextInputEditText, textColorResource: Int?) {
if (textColorResource != null) {
textInputEditText.setHintTextColor(ContextCompat.getColor(textInputEditText.context, textColorResource))
}
}
在您的XML
<data>
<variable
name="settings"
type="..censored..Settings" />
</data>
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
app:textColor="@{settings.primaryTextColor}"
app:textColorHint="@{settings.primaryHintColor}"
/>