Home > Software design >  How Can I change ConstraintLayout verticalBias according to viewState value
How Can I change ConstraintLayout verticalBias according to viewState value

Time:03-23

I have BindingAdapter like;

@JvmStatic
@BindingAdapter("setVerticalBias")
fun ConstraintLayout.setVerticalBias(value: Float?) {
    val cs = ConstraintSet()
    cs.setVerticalBias(R.id.llResultContent, value ?: 0.1f)
    cs.applyTo(this)
}

And I have condition in my viewState which is manage float value like;

val constraintBias: Float
    get() {
        return if (hasSecondaryActions) {
            0.1f
        } else {
            0.8f
        }
    }

Then I used that with my binding adapter like;

 <LinearLayout
        android:id="@ id/llResultContent"
        setVerticalBias="@{viewState.constraintBias}"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

So I'm getting this error

"Cannot find a setter for <android.widget.LinearLayout setVerticalBias> that accepts parameter type 'float' If a binding adapter provides the setter, check that the adapter is annotated correctly and that the parameter type matches. Open File"

What is the problem here I can't find it!

CodePudding user response:

setVerticalBias is set on the LinearLayout not the ConstraintLayout even though the bias is used by the ConstraintLayout. Change your binding adapter to the following:

@JvmStatic
@BindingAdapter("setVerticalBias")
fun LinearLayout.setVerticalBias(value: Float?) {
    val constraintLayout = (this.parent as ConstraintLayout)
    val cs = ConstraintSet()
    cs.clone(constraintLayout)
    cs.setVerticalBias(R.id.llResultContent, value ?: 0.1f)
    cs.applyTo(constraintLayout)
}

or, more generally:

@JvmStatic
@BindingAdapter("setVerticalBias")
fun LinearLayout.setVerticalBias(value: Float?) {
    val constraintLayout = (this.parent as ConstraintLayout)
    val cs = ConstraintSet()
    cs.clone(constraintLayout)
    cs.setVerticalBias(this.id, value ?: 0.1f)
    cs.applyTo(constraintLayout)
}
  • Related