ConstraintLayout,向上移动一个LinearLayout(负面)

问题描述 投票:0回答:2

我正在用Kotlin将一些项目迁移到AndroidX。我在使用ConstraintLayout时遇到了一些问题,根据文档我已经知道了:

ConstraintLayout不支持负边距。 [...]

但我有以下情况:

enter image description here

我需要在5dp向上移动LinearLayout,但是我需要高度继续匹配屏幕的下限。也就是说,我向上移动5dp并将高度增加5dp。

就像它在图像中一样,我已经尝试过translateY,但它只是移动整个视图(不是我需要的)。此外,我无法在id#top内创建一个高度为5dp的视图,并与constraintTop_toTopOf对齐,因为它们是不同组的一部分。

这种情况有什么解决方案吗?

android kotlin androidx
2个回答
1
投票

在ConstraintLayout中获取重叠视图很棘手,但您可以通过添加不可见视图并将重叠视图约束到不可见视图来实现。

在这种情况下,隐形视图的底部可以被约束到绿色LinearLayout的底部,底部边距为5dp。然后红色LinearLayout可以将其顶部约束到不可见视图的底部。这应该给你5dp的重叠。

尝试将以下内容复制粘贴到约束布局中

            <LinearLayout
                android:id="@+id/green"
                android:layout_width="0dp"
                android:layout_height="100dp"
                android:orientation="vertical"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                android:background="@android:color/holo_green_light" />

            <View
                android:id="@+id/dummyView"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_marginBottom="5dp"
                android:visibility="invisible"
                app:layout_constraintBottom_toBottomOf="@id/green"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"/>

            <LinearLayout
                android:id="@+id/red"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginStart="16dp"
                android:layout_marginEnd="16dp"
                android:orientation="vertical"
                app:layout_constraintTop_toBottomOf="@id/dummyView"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                android:background="@android:color/holo_red_light" />

请注意,在ConstraintLayout的子视图上设置时,维度“0dp”表示“匹配约束”。这并不明显,但实际上是在这里记录https://developer.android.com/reference/android/support/constraint/ConstraintLayout


0
投票

ConstraintLayout的整个目的是拥有一个平面视图层次结构。因此,嵌套LinearLayouts会失败的目的。

我建议你摆脱嵌套的LinearLayouts,并使用约束做一切。

© www.soinside.com 2019 - 2024. All rights reserved.