如何在Android中使用数据绑定动态地为ImageView设置图像资源

5

请问有人可以告诉我如何使用数据绑定来填充图像资源到ImageView中吗?

2个回答

2
你可以参考以下内容:
步骤1: 在文件中创建一个类似于这样的方法。
@BindingAdapter("set_expense_category_image")
fun ImageView.setImageResource(expenseCategory: String) {
    this.setImageResource(
        when (expenseCategory) {
            ExpenseTypes.FOOD.expenseLitral -> R.drawable.ic_baseline_fastfood_24
            ExpenseTypes.SHOPPING.expenseLitral -> R.drawable.ic_baseline_shopping_basket_24
            ExpenseTypes.GYM.expenseLitral -> R.drawable.ic_baseline_accessibility_new_24
            ExpenseTypes.MEDICAL.expenseLitral -> R.drawable.ic_baseline_medical_services_24
            ExpenseTypes.HOUSE_RENT.expenseLitral -> R.drawable.ic_baseline_house_24
            ExpenseTypes.TRAVEL.expenseLitral -> R.drawable.ic_baseline_emoji_transportation_24
            ExpenseTypes.FREE_HAND_MONEY.expenseLitral -> R.drawable.ic_outline_money_24
            ExpenseTypes.INVESTING.expenseLitral -> R.drawable.ic_baseline_monetization_on_24
            ExpenseTypes.MONTHLY_EMI.expenseLitral -> R.drawable.ic_baseline_payments_24
            ExpenseTypes.MISCELLANEOUS.expenseLitral -> R.drawable.ic_baseline_kitesurfing_24
            else -> R.drawable.ic_baseline_supervisor_account_24
        }
    )
}

步骤:2

您可以在图像视图中使用输入来加载动态图像,具体请参见以下内容:

<ImageView
            android:id="@+id/imageView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
             set_expense_category_image="@{expense.expenseCategoryName}"
            app:layout_constraintBottom_toTopOf="@+id/view"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/imageView5"
            app:srcCompat="@drawable/ic_baseline_fastfood_24" />

谢谢Adam,这正是我正在寻找的。 - Sam Curran

0

您可以这样使用它:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_padding="20dp"
    android:scaleType="centerInside"
    android:src="@{model.isActive ? @drawable/activated_icon :@drawable/non_activated_icon}"/>

更多信息可以在这里这里以及文档中找到。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接