我想要一个与屏幕一样宽和与其子级一样高的水平LinearLayout
,但诀窍是它的子级将具有动态宽度,我不希望它们离开屏幕(剪切(。我希望它们在新行中流动/中断,以便它们都可见。
虽然与Android完全无关,但它的工作方式应该类似于内联<div>
在HTML中的工作方式。
这是我现在拥有的:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="If you would enter some digits in this field " />
<EditText
android:id="@+id/tvDistance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="enter some digits here"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" that would be great" />
</LinearLayout>
但是一旦LinearLayout
的孩子变得比屏幕宽,额外的部分就会离开屏幕/不可见。
我想要一个水平的线性布局,它和 屏幕和它的孩子一样高,但诀窍是它的孩子 每个都有动态宽度,我不希望它们离开屏幕 (剪掉(。
LinearLayout
无法执行此操作(SDK 中的任何默认布局都无法执行此操作(,因为LinearLayout
设置为将所有子项放置在一条水平或垂直线上。此外,基于尚不可用的尺寸的任何类型的条件布局规则(例如在您的情况下,LinearLayout
的可用宽度(无论如何在 xml 中都是不可能的。
您需要的是一个自定义布局,该布局测量子项使用可用空间在下面的新行上移动任何不合适的子项(所谓的FlowLayout
(。
编辑:
谷歌现在提供了flexbox
库,该库在Android上实现了网络的flexbox布局。使用该库,FlexboxLayout
的子项将使用flexDirection
(值为行(和flexWrap
(值为换行(属性,根据其宽度放置在多行上。
除了Flexbox之外,您还可以使用ChipGroup,它是Material Design Library的一部分。ChipGroup
也可以是其他组件的容器,它不必是Chip
,它可以是一个按钮等。
一个芯片组用于持有多个芯片。默认情况下,芯片是跨多条线重排。将应用程序:单行属性设置为将芯片限制为一条水平线。如果你这样做,你将通常希望将此 ChipGroup 包装在水平滚动视图中。
<com.google.android.material.chip.ChipGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp">
<com.google.android.material.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:chipText="This" />
<com.google.android.material.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:chipText="is" />
<com.google.android.material.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:chipText="a" />
<com.google.android.material.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:chipText="because" />
<com.google.android.material.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:chipText="chip" />
<com.google.android.material.chip.Chip
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:chipText="group" />
</com.google.android.material.chip.ChipGroup>
更新:
从Constraint Layout 2.0
开始,我们现在可以使用Flow
<androidx.constraintlayout.helper.widget.Flow
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:flow_wrapMode="chain"
app:constraint_referenced_ids="card1, card2, card3"
/>
通知app:constraint_referenced_ids
和app:flow_wrapMode
第一个是关于传递视图,第二个是关于处理我们包装它们的方式。
请务必在官方文档中阅读有关它的信息