如何将一个视图限制在两个可见性可以切换的视图下方?
How to constrain a View below two Views whose visibility can be switched?
图像 a ConstraintLayout
包括三个垂直堆叠的项目:
@+id/top
@+id/middle1 or @+id/middle2 (one gets View.VISIBLE, one gets View.GONE)
@+id/bottom
@+id/middle1
和 @+id/middle2
的顶部被限制在 @+id/top
的底部,这里没有问题。
有趣的案例是@+id/bottom
。它应始终放在 @+id/middle1
或 @+id/middle2
下方,具体取决于哪个可见(另一个将显示 View.GONE
)。有没有什么方法可以在布局文件中对此进行建模,或者我是否必须在显示 @+id/middle1
和 @+id/middle2
之间切换时更改 @+id/bottom
的顶部约束?
正如 CommonsWare 所提议的那样,它可以用 Barrier
来完成,如下所示:
<androidx.constraintlayout.widget.Barrier
android:id="@+id/barrier"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="bottom"
app:barrierAllowsGoneWidgets="false"
app:constraint_referenced_ids="middle1,middle2" />
注意 app:constraint_referenced_ids
中的 ID 没有 @id/
前缀。
因为我的 middle1
和 middle2
有不同的高度,我将其中之一设置为 View.GONE
我选择了 app:barrierAllowsGoneWidgets="false"
以确保 Barrier
位置得到更新,没有留下空白 space。
有关详细信息,请参阅 official documentation or e.g. on Youtube the video ConstraintLayout Tutorial Part 4 - BARRIERS AND GROUPS - Android Studio Tutorial
图像 a ConstraintLayout
包括三个垂直堆叠的项目:
@+id/top
@+id/middle1 or @+id/middle2 (one gets View.VISIBLE, one gets View.GONE)
@+id/bottom
@+id/middle1
和 @+id/middle2
的顶部被限制在 @+id/top
的底部,这里没有问题。
有趣的案例是@+id/bottom
。它应始终放在 @+id/middle1
或 @+id/middle2
下方,具体取决于哪个可见(另一个将显示 View.GONE
)。有没有什么方法可以在布局文件中对此进行建模,或者我是否必须在显示 @+id/middle1
和 @+id/middle2
之间切换时更改 @+id/bottom
的顶部约束?
正如 CommonsWare 所提议的那样,它可以用 Barrier
来完成,如下所示:
<androidx.constraintlayout.widget.Barrier
android:id="@+id/barrier"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="bottom"
app:barrierAllowsGoneWidgets="false"
app:constraint_referenced_ids="middle1,middle2" />
注意 app:constraint_referenced_ids
中的 ID 没有 @id/
前缀。
因为我的 middle1
和 middle2
有不同的高度,我将其中之一设置为 View.GONE
我选择了 app:barrierAllowsGoneWidgets="false"
以确保 Barrier
位置得到更新,没有留下空白 space。
有关详细信息,请参阅 official documentation or e.g. on Youtube the video ConstraintLayout Tutorial Part 4 - BARRIERS AND GROUPS - Android Studio Tutorial