5

can someone let me know the right usage of populating image resource in Image view using Data Binding

Sam Curran
  • 53
  • 3

2 Answers2

2

you can refer this:

Step : 1

Create a method in a file like this

@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
        }
    )
}

Step:2

You can use the in the image view for loading dynamic images based on input, refer below:

<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" />
0

You can use it in such way:

<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}"/>

more info can be found here and here plus docs.

Andrew
  • 1,947
  • 2
  • 23
  • 61