【发布时间】: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 来演示问题
【问题讨论】:
-
感谢您的回复和链接。很有趣,我能理解。我无法理解的是,为什么在从 ConstraintLayout 切换到任何其他 ViewGroup(FrameLayout、LinearLayout、GridLayout 等)之后,我在父布局上使用单个 requestLayout() 时一切正常?在我看来,任何 ViewGroup 都应该在改变大小后重新测量它的孩子,因为一些孩子可能希望拥有比以前更多的空间。至少 ViewGroups 允许他们的孩子使用非固定大小(约束、拉伸等)
标签: android android-layout android-constraintlayout