2017-06-14 117 views
0

我想在我的xml代码中绑定一个layout_marginBottom。并用Observable变量将此绑定链接到代码中。是否有可能用可观察数据绑定保证金?

我试图把数据绑定在我看来是这样的:

android:layout_marginBottom="@{viewModel.marginBottom}" 

然后在我的代码有:

public final ObservableFloat marginBottom = new ObservableFloat(0); 

但这不会编译,该错误信息是:

Error:(12, 36) Cannot find the setter for attribute 'android:layout_marginBottom' with parameter type float on com.example.customView. 

我试着用ObservableInt也是类似的错误信息。也许我必须以某种方式将int转换为dp?这可能吗?我如何完成这项工作?

回答

0

您不应该通过数据绑定来控制布局。但是如果你真的想这样做,那么编写一个@BindingAdapter作为修改ViewLayoutParams的边距应该是完全正确的。

@BindingAdapter("layout_marginBottom") 
public static void setMarginBottom(View view, int margin) { 
    ViewGroup.LayoutParams params = view.getLayoutParams(); 
    if (params instanceof ViewGroup.MarginLayoutParams) { 
     ViewGroup.MarginLayoutParams margins = (ViewGroup.MarginLayoutParams) params; 
     margins.bottomMargin = margin; 
     view.requestLayout(); 
    } 
}