Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Databinding width with ternary using dp in XML

I know I can use @dimen/something... but was wondering why this does not work and how to get it to work. Will help me understand the black box of databinding parser.

In my XML for a lineralayout element:

android:layout_width="@{DataBoundData.dis.equals(IN_PROGRESS) ? 60dp : 
     (DataBoundData.dis.equals(POSTED) ? 60dp : 0dp)}"

It shows an error on the 'p' in 60dp. I have tried 60d\p 60dp and a few others and nothing works

like image 562
JPM Avatar asked Oct 12 '17 19:10

JPM


1 Answers

To answer the question of why android:layout_width="@{60dp}" doesn't work, it is because data binding doesn't understand the concept of 'dp'.

You've already created some kind of BindingAdapter for the attribute or it wouldn't work at all, because layout_width isn't supported by default. Maybe you have something like this:

@BindingAdapter("android:layout_width")
public static void setLayoutWidth(View view, float width) {
    LayoutParams layoutParams = view.getLayoutParams();
    layoutParams.width = (int)width;
    view.setLayoutParams(layoutParams);
}

There is no indication on the BindingAdapter what the float width is. It has no type, so there is no way to transfer that knowledge to the constants in the data binding system. It is the same reason you must use

android:visibility="@{View.INVISIBLE}"

instead of

android:visibility="@{invisible}"

There is no java constant invisible in the context of setting the int value on setVisibility()

You can pass in an integer constant like 60 and it will assign it. Unfortunately, those are pixels for LayoutParams and that changes between devices.

When you use @dimen/someDimension, data binding converts the dimension into an float at the time the value is extracted from the resources. That's easy to understand because Resources.getDimension() returns a float. Likewise, Resources.getColor() returns an integer, so every time you pass a color resource, you're passing an integer around.

Hope that helps.

like image 150
George Mount Avatar answered Nov 09 '22 04:11

George Mount