代码B运行良好。
aHomeViewModel.isHaveRecord
是LiveData<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}" />
测试和工作;(