Android数据绑定 - 如何从dimens.xml获取维度

j2e*_*nue 15 data-binding android

我想根据我在dimens.xml中创建的维度设置边距它自己的尺寸很好,它只是数据绑定在下面的情况下找不到它:

<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" />
Run Code Online (Sandbox Code Playgroud)

它确实找到了它,但它说marginbottom不能采用float类型.我怎样才能解决这个问题?我尝试将这两个维度转换为int,但后来却抱怨它无法转换为int.

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

    <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>
Run Code Online (Sandbox Code Playgroud)

Geo*_*unt 34

这里的问题不是尺寸,而是尺寸android:layout_marginBottom.没有任何LayoutParams属性的内置支持.这样做是为了删除许多可能用来绑定变量的"脚枪",LayoutParams并且可能尝试使用数据绑定来以这种方式设置其位置的动画.

数据绑定非常适合在您的示例中使用,您可以轻松添加自己的数据绑定.这将是这样的.

@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);
}
Run Code Online (Sandbox Code Playgroud)

当然,您也可以添加左,上,右,开始和结束BindingAdapters.

  • @GeorgeMount,我发现在AS 2.2预览版6中,我需要将bottomMargin的类型设置为float而不是int,否则我会得到编译错误,说_Cannot找到属性'android:layout_marginBottom'的setter,参数类型为float on android.widget.TextView_ (6认同)
  • 不,这不是一个bug.`@ dimen`资源是浮点数,而`@ dimenOffset`和`@ dimenSize`是整数.这分别对应于Resources.getDimension(),getDimensionPixelSize()和getDimensionPixelOffset().采用浮点数总是安全的,因为int会自动转换为浮点数,但浮点数不会自动转换为整数. (4认同)
  • 我应该在哪里编写此代码?我指定marginBottom的所有布局都将使用此方法还是仅使用数据绑定布局,还是仅使用此特定布局? (2认同)