资源绑定的数据绑定编译错误

时间:2020-08-16 17:05:27

标签: android android-databinding

使用数据绑定时出现此错误:

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;

我真的不明白哪里出了问题。

1 个答案:

答案 0 :(得分:2)

您尚未传递context,它是函数的第一个参数。您可以将函数的用法重构为:

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

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