Databindingでcolorかdrawableを条件によって設定したいとき
条件によってviewのbackgroundをcolor resourceかdrawable resourceか変更したいとき
backgroundに"@{ContextCompat.getDrawable(context,isGrayBackground ? @color/gray : @drawable/pattern_bg)}"
のように記載するとbuildエラーが出る。
現象
<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:bind="http://schemas.android.com/tools"> <data> <variable name="isGrayBackground" type="Boolean" /> <import type="androidx.core.content.ContextCompat" /> <import type="com.quipper.school.assignment.ui.dashboard.home.ViewState" /> </data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@{ContextCompat.getDrawable(context,isGrayBackground ? @color/gray : @drawable/pattern_bg)}" </layout
Error messageは以下。
must be able to find a common parent for int and android.graphics.drawable.drawable
また、以下のように変更してもエラーが出てしまう。
android:background="@{isGrayBackground? ContextCompat.getDrawable(context,@color/gray) : ContextCompat.getDrawable(context,@drawable/pattern_bg)}"
cannot find method getDrawable(android.content.Context, android.graphics.drawable.Drawable) in class androidx.core.content.ContextCompat
解決策
動的にbackground attributeにcolorかdrawableかを設定するのは厳しいぽいのでcolor resourceをdrawable resourceにして設定する。
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/gray_minus_3" /> </shape>
android:background="@{isGrayBackground ? @drawable/bg_gray) : @drawable/pattern_bg}"/>
layout全体
<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:bind="http://schemas.android.com/tools"> <data> <variable name="isGrayBackground" type="Boolean" /> <import type="androidx.core.content.ContextCompat" /> <import type="com.quipper.school.assignment.ui.dashboard.home.ViewState" /> </data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@{isGrayBackground ? @drawable/bg_gray) : @drawable/pattern_bg}"/> </layout