【问题标题】:Troubles with changing FrameLayout size with ConstraintLayout child使用 ConstraintLayout child 更改 FrameLayout 大小的问题
【发布时间】:2021-01-06 13:21:46
【问题描述】:

我有 FrameLayout,里面有 ConstraintLayout。 ConstraintLayout 具有android:layout_height="wrap_content" 属性。 FrameLayout 具有固定大小,小于 ConstraintLayout 所需的大小。我希望当我在运行时增加 FrameLayout 高度时, ConstraintLayout 的高度也会增加,直到它适合内容。但它不会发生。如果我切换到 FrameLayout 而不是 ConstraintLayout,或者如果我直接在 ConstraintLayout 上调用 requestLayout(),它会按预期工作。这种行为的原因可能是什么?

布局:

 <FrameLayout
            android:id="@+id/view2"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_marginBottom="16dp"
            android:background="@drawable/frame_layout_bg">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/constraint_layout_bg">

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="top|center_horizontal"
                    android:padding="16dp"
                    android:text="Constraint layout content"
                    android:textSize="24sp"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />
            </androidx.constraintlayout.widget.ConstraintLayout>
        </FrameLayout>

更改高度代码:

        val frameLayout = findViewById<ViewGroup>(res)

        val finalHeight = TypedValue
            .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100f, resources.displayMetrics)
            .toInt()

        val layoutParams = frameLayout.layoutParams
        layoutParams.height = finalHeight

        frameLayout.layoutParams = layoutParams
        frameLayout.requestLayout()

创建example project 来演示问题

【问题讨论】:

  • 为父布局调用 requestLayout() 不会重新测量子布局。你应该用parent.requestLayout() 打电话给child.forceLayout(),或者你说你应该直接打电话给child.requestLayout()。您可以阅读thisthis 以获取更多信息。
  • 感谢您的回复和链接。很有趣,我能理解。我无法理解的是,为什么在从 ConstraintLayout 切换到任何其他 ViewGroup(FrameLayout、LinearLayout、GridLayout 等)之后,我在父布局上使用单个 requestLayout() 时一切正常?在我看来,任何 ViewGroup 都应该在改变大小后重新测量它的孩子,因为一些孩子可能希望拥有比以前更多的空间。至少 ViewGroups 允许他们的孩子使用非固定大小(约束、拉伸等)

标签: android android-layout android-constraintlayout


【解决方案1】:

这似乎是从 2.0.2 版本开始的 ConstraintLayout 中的一个错误,我刚刚创建了一个 pull request 建议修复此问题希望它会尽快修复,您可以切换回 2.0.1 到避免这个问题,直到它在未来的版本中得到解决

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多