如何在 Android Studio 中为 android:layout_marginLeft 的 LiveData 绑定不同的值<Boolean>?



代码B运行良好。

aHomeViewModel.isHaveRecordLiveData<Boolean>,我希望根据aHomeViewModel.isHaveRecord的值设置不同的marginLeft

Bur代码A出现以下编译错误,我该如何修复?

找不到<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>

顺便说一句,下面的代码可以很好地工作。

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

要实现这一点,您必须定义一个自定义@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}" />

测试和工作;(

最新更新