本文介绍了Android数据绑定 - 如何从维度中获取维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据维度在dimension.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:

<TextView
           android:id="@+id/title_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/disableButton"
*************
        android:layout_marginBottom="@{@bool/showAds ? 
@dimen/frontpage_margin_ads: @dimen/frontpage_margin_noads}"
*************        
android:gravity="center_horizontal"
        android:text="@string/app_name"
        android:textColor="@android:color/holo_orange_dark"
        android:contentDescription="@string/app_name"
        android:textSize="64sp"
        android:textStyle="bold" />

它找到它,但它表示marginbottom不能使用类型float。我如何解决这个问题?我尝试将二维转换为int,但是它抱怨它不能被转换为int。

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.

我的维度xml文件如下所示:

My dimensions xml file looks like this:

    <resources>

    <!-- 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>


</resources>


推荐答案

这里的问题不在于维度, code> android:layout_marginBottom 。任何 LayoutParams 属性没有内置的支持。这样做是为了删除许多可能用来将变量绑定到 LayoutParams 的脚枪,并且可能尝试使用数据绑定来以这种方式动画化他们的位置。

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.

@BindingAdapter("android:layout_marginBottom")
public static void setBottomMargin(View view, float bottomMargin) {
    MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams();
    layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin,
        layoutParams.rightMargin, Math.round(bottomMargin));
    view.setLayoutParams(layoutParams);
}

当然,你也会添加左,上,右,开始,并结束 BindingAdapters

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

这篇关于Android数据绑定 - 如何从维度中获取维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 16:39