具有数据绑定的ConstraintLayout [英] ConstraintLayout with databinding

查看:45
本文介绍了具有数据绑定的ConstraintLayout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以执行以下操作:

Is it possible to do something like this:

Xml:

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

ViewModel:

ViewModel:

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

我收到此错误:

找不到属性的设置器 参数类型为float的"app:layout_constraintGuide_percent" android.support.constraint.Guideline.

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

我已经尝试使用BindingAdaptor,但它不会更改值:

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

ViewModel:

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.

推荐答案

此问题可能与 Android数据绑定有关无法设置layout_width(layout_height)属性.无论如何,将以下代码添加到ViewModel:

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

您的Guideline的XML如下所示:

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.

这篇关于具有数据绑定的ConstraintLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆