2

代码 B 运行良好。

aHomeViewModel.isHaveRecord就是LiveData<Boolean>,我希望设置不同marginLeft的基础值aHomeViewModel.isHaveRecord

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

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

代码 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>

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

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

1 回答 1

4

要使其正常工作,您必须定义一个自定义@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 的父级。

要使用它,请将您的 xml 调整为:

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

测试和工作;)

于 2020-11-04T11:59:20.413 回答