数据绑定布局约束

时间:2018-11-28 08:00:10

标签: android android-constraintlayout android-databinding

我无法添加结束约束以查看

 <android.support.constraint.ConstraintLayout
    android:id="@+id/chatDocumentMessageContent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@{chatMessage.corespondent==Corespondent.Sent? @drawable/very_rounded_corners_gray_background:@drawable/very_rounded_corners_orange_background}"
    android:maxWidth="300dp"
    android:minWidth="140dp"
    android:onClick="@{clickListener::onClick}"
    android:padding="@dimen/padding_large"
    app:layout_constraintEnd_toEndOf="@{chatMessage.corespondent==Corespondent.Sent? ConstraintSet.PARENT_ID:ConstraintSet.UNSET}">

我收到此错误:

  

[kapt]发生异常:   android.databinding.tool.util.LoggedErrorException:找到了数据绑定   错误。   **** /数据绑定错误**** msg:找不到参数类型为int的属性'app:layout_constraintEnd_toEndOf'的设置方法   android.support.constraint.ConstraintLayout。

尝试添加以下适配器,但仍然无法正常工作:

 @BindingAdapter(" app:layout_constraintEnd_toEndOf")
    fun setEndConstraint(guideline: Guideline, resource: Int) {
        val params = guideline.getLayoutParams() as ConstraintLayout.LayoutParams
        params.endToEnd = resource
        guideline.layoutParams = params
    }

1 个答案:

答案 0 :(得分:1)

我为这种情况创建了BindingAdapter:

@BindingAdapter(
    "layout_conditionalConstraint_startSide",
    "layout_conditionalConstraint_toEndId",
    "layout_conditionalConstraint_endSide",
    "layout_conditionalConstraint_condition"
)
fun setConditionalConstraint(
    view: View, startSide: Int, endId: Int, endSide: Int, condition: Boolean
) {
    val constraintLayout = (view.parent as? ConstraintLayout) ?: return
    with(ConstraintSet()) {
        clone(constraintLayout)
        if (condition) connect(view.id, startSide, endId, endSide)
        else clear(view.id, startSide)
        applyTo(constraintLayout)
    }
}

在您的情况下,您可以这样使用它:

<android.support.constraint.ConstraintLayout
    android:id="@+id/chatDocumentMessageContent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@{chatMessage.corespondent == Corespondent.Sent ? @drawable/very_rounded_corners_gray_background : @drawable/very_rounded_corners_orange_background}"
    android:maxWidth="300dp"
    android:minWidth="140dp"
    android:onClick="@{clickListener::onClick}"
    android:padding="@dimen/padding_large"
    app:layout_conditionalConstraint_startSide="@{ConstraintSet.END}"
    app:layout_conditionalConstraint_toEndId="@{ConstraintSet.PARENT_ID}"
    app:layout_conditionalConstraint_endSide="@{ConstraintSet.END}"
    app:layout_conditionalConstraint_condition="@{chatMessage.corespondent == Corespondent.Sent}">

但是在大​​多数情况下,您应该能够使用ConstraintLayout提供的功能来获得所需的布局,此BindingAdapter仅在少数角落情况或复杂的布局中有用。