资源的数据绑定编译错误

Databinding compile error with ressources

我在使用数据绑定时遇到这个错误:

A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution

我尝试在绑定中添加颜色函数:

object Colors {

    fun getGradeColor(context: Context, grade: String): Int {
        val color =  when (grade.toUpperCase(Locale.getDefault())) {
            "A" -> R.color.grade_a
            "B" -> R.color.grade_b
            "C" -> R.color.grade_c
            "D" -> R.color.grade_d
            else -> R.color.grade_e
        }
        return ContextCompat.getColor(context, color)
    }

}

这是我的布局数据:

 <data>
        <import type="androidx.core.content.ContextCompat"/>
        <variable
            name="colors"
            type="com.myapp.utils.Colors"/>
        <variable
            name="clickListener"
            type="android.view.View.OnClickListener"/>
        <variable
            name="digitalService"
            type="com.myapp.api.response.DigitalService"/>
    </data>

当我使用时:

android:backgroundTint="@{colors.getGradeColor(digitalService.score.grade)}"

使用 compileDebugKotlin,我有这个错误:

ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1/Users/jerome/StudioProjects/myapp/app/build/generated/source/kapt/debug/com/myapp/DataBinderMapperImpl.java:16: error: cannot find symbol
import com.myapp.databinding.ItemDigitalServiceBindingImpl;

我真的不明白哪里不对。

您还没有传递函数的第一个参数 context。您可以将函数的用法重构为:

android:backgroundTint="@{colors.getGradeColor(context,digitalService.score.grade)}"

生成一个名为 context 的变量用于绑定。这使用根视图上下文。