j2emanue j2emanue - 9 months ago 62
Android Question

Android databinding - How to get dimensions from dimens.xml

I want to set margins based on dimensions i have created in dimens.xml The dimensions it sself works fine, its just data binding cant find it in the case below:

android:layout_marginBottom="@{@bool/showAds ?
@dimen/frontpage_margin_ads: @dimen/frontpage_margin_noads}"
android:textStyle="bold" />

it did find it but it says that marginbottom cannot take type float. How can i fix this? I tried casting both dimens to int but then it complains that it cannot be casted to int.

My dimensions xml file looks like this:


<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="bigText">44sp</dimen>
<dimen name="littleText">44sp</dimen>
<dimen name="mediumText">40sp</dimen>
<dimen name="smallText">24sp</dimen>
<dimen name="fab_margin">16dp</dimen>
<dimen name="frontpage_margin_noads">0dp</dimen>
<dimen name="frontpage_margin_ads">13dp</dimen>


Answer Source

The problem here is not with dimensions, but with android:layout_marginBottom. There is no built-in support for any LayoutParams attributes. This was done to remove the "foot gun" that many might use to bind variables to LayoutParams and maybe attempt to use data binding to animate their positions this way.

Data Binding is perfect to be used in your example and you can easily add your own. It would be something like this.

public static void setBottomMargin(View view, int bottomMargin) {
    MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams();
    layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin,
        layoutParams.rightMargin, bottomMargin);

You would, of course, also add the left, top, right, start, and end BindingAdapters as well.