I'm trying to bind a boolean that points to an ImageView if the screen size is small, so it shrinks if I need more space for other components. For this, I use the DataBinding Library .
My layout, the width and height of which depends on this boolean:
... <data> ... <variable name="smallScreen" type="boolean"/> ... </data> ... <ImageView android:layout_width="@{smallScreen ? @dimen/img_small_screen_size : @dimen/img_big_screen_size}" android:layout_height="@{smallScreen ? @dimen/img_small_screen_size : @dimen/img_big_screen_size}" android:layout_gravity="center_horizontal" android:contentDescription="@{message}" android:src="@{image}" android:scaleType="center" tools:src="@drawable/img_message_private"/> ...
If I just try to build my project like this, the compiler says that layout_width cannot accept float type. Fair enough, I use the BindingAdapter class to create float input for layout attributes, as shown below:
... @BindingAdapter("android:layout_width") public static void setLayoutWidth(View view, float width) { ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); layoutParams.width = (int) width; view.setLayoutParams(layoutParams); } @BindingAdapter("android:layout_height") public static void setLayoutHeight(View view, float height) { ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); layoutParams.height = (int) height; view.setLayoutParams(layoutParams); } ...
This allows my project to build. But when the layout is finally displayed, I get the following exception:
java.lang.RuntimeException: Binary XML file line
For information only, my sizes are given in dp units, as shown below:
<dimen name="img_small_screen_size">100dp</dimen> <dimen name="img_big_screen_size">208dp</dimen>
Does anyone know how I can override the layout_width attribute so that I can directly use data binding with it using dimensions?
source share