带数据绑定的ConstraintLayout

时间:2017-06-30 11:13:27

标签: android android-databinding android-constraintlayout

是否可以做这样的事情:

XML:     

        <android.support.constraint.Guideline
             app:layout_constraintGuide_percent="@{viewModel.guidelinePercent}"
        />

ViewModel:

  @Bindable
    public float getGuidelinePercent() {
        return condition ? 0.6f : 0.8f;
    }

我收到了这个错误:

  

找不到属性的setter   'app:layout_constraintGuide_percent',参数类型为float on   android.support.constraint.Guideline。

我尝试过使用BindingAdaptor,但它没有更改值:

视图模型:

@BindingAdapter(value = {"constraintPercent"})
public static void setConstraintPercent(Guideline view, float percent){
    ConstraintSet constraintSet = new ConstraintSet();
    constraintSet.setGuidelinePercent(view.getId(), percent);
}

XML:

<android.support.constraint.Guideline
                 app:constraintPercent="@{viewModel.guidelinePercent}"
            />

有什么想法吗? 感谢。

2 个答案:

答案 0 :(得分:7)

此问题可能与Android Databinding cannot set the layout_width (layout_height) property有关。无论如何,请将以下代码添加到ViewModel

public float getGuidelinePercent() {
    return 0.5f; // Of course, this default could be anything you want.
}

@BindingAdapter("layout_constraintGuide_begin")
public static void setLayoutConstraintGuideBegin(Guideline guideline, float percent) {
    ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) guideline.getLayoutParams();
    params.guidePercent = percent;
    guideline.setLayoutParams(params);
}

Guideline的XML看起来像这样:

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="@{viewModel.guidelinePercent}"/>
顺便说一句,谢谢你的想法。我一直想要一种更简单的方法来以编程方式调整指南。

答案 1 :(得分:2)

在设置百分位数后的某个时间,您创建的ConstraintSet应设置为ConstraintLayout

@BindingAdapter(value = {"constraintPercent"})
public static void setConstraintPercent(Guideline view, float percent){
    ConstraintLayout constraintLayout = (ConstraintLayout) view.getParent();
    ConstraintSet constraintSet = new ConstraintSet();
    constraintSet.clone(constraintLayout);
    constraintSet.setGuidelinePercent(view.getId(), percent);
    constraintLayout.setConstraintSet(constraintSet);
}