首页 > 解决方案 > Android 数据绑定 - 如何为 ImageView 设置 contentDescription 和 src

问题描述

我正在尝试这样设置contentDescription

        <ImageView
        android:id="@+id/accountType"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:contentDescription="@{() -> account.getContentDescription()}"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@mipmap/ic_launcher" />

我的帐户类:

data class Account(
    val id: Long = 0L,
    val title: String,
    val accountType: AccountType,
    val balance: Double = 0.0
) {
fun getAccountTypeDrawable() =
        when (accountType) {
            AccountType.CHECKING_ACCOUNT -> R.drawable.ic_account_balance_black_48dp
            AccountType.WALLET -> R.drawable.ic_local_atm_black_48dp
            AccountType.SAVINGS_ACCOUNT -> R.drawable.ic_package_black_48dp
            AccountType.INVESTMENT -> R.drawable.ic_trending_up_black_48dp
            AccountType.OTHER -> R.drawable.ic_lens_black_48dp
        }

fun getContentDescription(view: View) =
        view.context.resources.getStringArray(R.array.account_type)[accountType.ordinal]!!
}

我收到此错误:

e: [kapt] 发生异常:android.databinding.tool.util.LoggedErrorException: 发现数据绑定错误。****/ 数据绑定错误 ****msg:Cannot find the proper callback class for android:contentDescription. 试过 java.lang.CharSequence 但它有 4 个抽象方法,应该有 1 个抽象方法。文件:C:\Users\Douglas\AndroidStudioProjects\Currency\app\src\main\res\layout\item_account.xml loc:23:42 - 23:78 ****\数据绑定错误 ****

如果我像这样直接在 xml 中设置,它将按预期工作:

android:contentDescription="@{context.getResources().getStringArray(R.array.account_type)[account.accountType.ordinal]}"

但是我在 Account 类中创建了该方法,以避免一直这样做。

如何设置contentDescriptionapp:srcCompat使用ImageViewAccount 类中的方法?

标签: androidandroid-databinding

解决方案


您可以直接使用上下文:

android:contentDescription="@{account.getContentDescription(context)}"

推荐阅读