Set constraint height percent with databinding

Viewed 152

I have a bar that should have a height according to the viewmodel.heartStrengthLiveData value (0..100). I want to set height with app:layout_constraintHeight_percent="..." with databinding. How can i do this?

enter image description here

            <androidx.constraintlayout.widget.ConstraintLayout
                android:id="@+id/heart_strength_bgc"
                android:layout_width="@dimen/cardiogram_status_bar_width"
                android:layout_height="0dp"
                android:layout_marginEnd="@dimen/default_screen_margin"
                android:background="@drawable/chart_widget_background_dark_gray"
                app:layout_constraintBottom_toBottomOf="@+id/cardiogram_background_light"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="@+id/cardiogram_background_light" >

                <androidx.constraintlayout.widget.ConstraintLayout
                    android:id="@+id/heart_strength"
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    app:heartStrength="@{viewmodel.heartStrengthLiveData}"
                    android:background="@drawable/chart_widget_background_light_gray"
                    android:backgroundTint="@color/turquoise"
                    app:layout_constraintHeight_percent="0"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent" />

            </androidx.constraintlayout.widget.ConstraintLayout>
1 Answers

Update: Corrected XML.

In your ViewModel, set up something like this which include the LiveData and the BindingAdapter for the layout percent height attribute:

public MutableLiveData heartStrengthLiveData = new MutableLiveData<>(100f);

public float getHeartStrength() {
    return (float) heartStrengthLiveData.getValue() / 100f;
}

@BindingAdapter("layout_constraintHeight_percent")
public static void setLayoutConstraintHeightPercent(View view, float percentHeight) {

    ConstraintLayout layout = (ConstraintLayout) view.getParent();
    ConstraintSet cs = new ConstraintSet();
    cs.clone(layout);
    cs.constrainPercentHeight(view.getId(), percentHeight);
    cs.applyTo(layout);
}

In the layout, specify:

app:layout_constraintHeight_percent='@{viewmodel.heartStrength}'
app:layout_constraintHeight_default="percent"

A height percentage of 1.0 will not work if the default height is not set to "percent" which addresses the issue in your (now deleted) comment.

Related