android - 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 类中创建了该方法,以避免一直这样做。
如何设置contentDescription
和app:srcCompat
使用ImageView
Account 类中的方法?
解决方案
您可以直接使用上下文:
android:contentDescription="@{account.getContentDescription(context)}"
推荐阅读
- nginx - NGInx log_format 从 $http_referrer 中删除任何敏感数据
- python - Pandas Groupby-根据组变化添加顺序元素
- css - 为什么我的 CSS 网格会创建四列而不是一列?
- javascript - Webpack 加载器错误:您可能需要额外的加载器来处理这些加载器的结果
- javascript - Vue:把方法变成承诺?
- javascript - 是否可以用 sprotty 创建一个 python dash 组件
- unity3d - Unity 纹理在垂直表面上显示为线条
- php - Slim 的问题——HttpNotFoundException
- python - 如何使用 Candlestick 从 plotly (Python) 制作动画
- javascript - 如何从浏览器启动批处理文件?