Android:如何动态调整约束视图布局适用于孩子的大小

时间:2021-06-12 09:21:29

标签: android constraints

我有一个 ContraintLayout 视图,其中有一个标签和一个徽章:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="@dimen/px350dp"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">

<TextView
    android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginTop="@dimen/px30dp"
    android:textSize="@dimen/px50dp"
    android:text="123.00"/>

<TextView
    android:id="@+id/badge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toRightOf="@id/label"
    app:layout_constraintTop_toTopOf="parent"
    android:text="Send"/>

</androidx.constraintlayout.widget.ConstraintLayout>

enter image description here

但是,当标签太长时,徽章会被推到容器外,不被接受。 enter image description here

解决方案之一是将徽章的约束更改为从父级到父级的约束。短的是,在某些场景中,距离有点远,像这样: enter image description here

因此,我需要一个解决方案来解决此类问题。正如我所想的那样,徽章会尽可能靠近标签,直到它到达边缘。需要您的帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

我得到了答案。在自定义视图中,在 onLayout 事件中重新布局。

class TextLabelView : ConstraintLayout {
   ...
   override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)

        badgeCtl?.let {
            if ((this.width - textCtl.width) / 2  - it.marginLeft < it.width) {
                val x = this.width - it.width
                it.layout(x, 0, it.measuredWidth + x, it.measuredHeight)
            }
        }
    }
}
相关问题