【问题标题】:Databinding textColor from variable来自变量的数据绑定 textColor
【发布时间】:2020-04-26 17:36:15
【问题描述】:

我想将数据绑定与 xml 中的颜色变量一起使用。 这是我的代码:

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”的设置器

如何使用变量实现数据绑定颜色?

【问题讨论】:

    标签: android data-binding android-databinding


    【解决方案1】:

    您可以为此使用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}"
                    />
    

    【讨论】:

    • 我必须在哪里调用这个 bindTextColor 函数?
    • 不,您不必调用该函数。您只需要将这些行添加到您的 XML 文件中。 app:textColor="@{settings.primaryTextColor}" app:textColorHint="@{settings.primaryHintColor}"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    相关资源
    最近更新 更多