如何为基于android:layout_marginLeft的LiveData< Boolean>绑定不同的值在Android Studio中? [英] How can I binding different value for android:layout_marginLeft based LiveData<Boolean> in Android Studio?

查看:83
本文介绍了如何为基于android:layout_marginLeft的LiveData< Boolean>绑定不同的值在Android Studio中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码B很好用.

aHomeViewModel.isHaveRecord LiveData< Boolean> ,我希望根据 aHomeViewModel.isHaveRecord .

Bur Code A收到以下编译错误,我该如何解决?

Bur Code A get the following compile error, how can I fix it?

找不到< android.widget.TextView的设置器android:layout_marginLeft>接受参数类型'float'

代码A

<TextView
     android:id="@+id/title_Date"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
    android:layout_marginLeft="@{aHomeViewModel.isHaveRecord? @dimen/margin1: @dimen/margin2 }"
  />

  <dimen name="margin1">10dp</dimen>
  <dimen name="margin2">5dp</dimen>

代码B

 <TextView
     android:id="@+id/title_Date"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_marginLeft="@dimen/margin1"
  />

  <dimen name="margin1">10dp</dimen>
  <dimen name="margin2">5dp</dimen>

顺便说一句,以下代码可以正常工作.

BTW, the following code can work well.

android:padding="@{aHomeViewModel.displayCheckBox? @dimen/margin1 : @dimen/margin2 }"

推荐答案

要使其正常工作,您将必须定义一个自定义 @BindingAdapter :

To get this working you will have to define a custom @BindingAdapter:

public class BindingAdapters {
    @BindingAdapter("marginLeftRecord")
    public static void setLeftMargin(View view, boolean hasRecord) {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
        params.setMargins(
                hasRecord ? (int) view.getResources().getDimension(R.dimen.margin1)
                          : (int) view.getResources().getDimension(R.dimen.margin2)
                , 0, 0, 0);
        view.setLayoutParams(params);
    }
}

是否需要 LinearLayout.LayoutParams 或其他取决于您TextView的父级.

Whether you need LinearLayout.LayoutParams or others depends on the parent of you TextView.

要使用此功能,请将xml调整为:

To use this adjust your xml to:

<TextView
    android:id="@+id/title_Date"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    marginLeftRecord="@{aHomeViewModel.isHaveRecord}" />

经过测试,可以正常工作;)

Tested and working ;)

这篇关于如何为基于android:layout_marginLeft的LiveData&lt; Boolean&gt;绑定不同的值在Android Studio中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆