ConstraintLayout with databinding

帅比萌擦擦* 提交于 2020-02-22 15:33:26

问题


Is it possible to do something like this:

Xml:

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

ViewModel:

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

I'm getting this error:

Cannot find the setter for attribute 'app:layout_constraintGuide_percent' with parameter type float on android.support.constraint.Guideline.

I've tried with BindingAdaptor but it doesn't change the value:

ViewModel:

@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}"
            />

Any thoughts?
Thanks.


回答1:


This issue may be related to Android Databinding cannot set the layout_width (layout_height) property. In any case, add the following code to 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);
}

Your XML for the Guideline will look something like this:

    <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}"/>

btw, thanks for this idea. I have been wanting an easier way to adjust guidelines programmatically.




回答2:


The ConstraintSet you're creating should be set to the ConstraintLayout sometime after setting the percentile.

@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);
}


来源:https://stackoverflow.com/questions/44845121/constraintlayout-with-databinding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!