我在布局中有2个视图 - TextView和Button。 TextView对齐/固定在左侧,按钮在右侧。
我想要实现的是Button的自然“包裹行为”。当TextView足够宽以便按钮没有空间(在同一行中)时,它应该移动到TextView下方,同时仍然固定在右侧。
以下是我想要实现的布局的3个场景:
我试图用FlexBoxLayout制作它,但是在包装后按钮出现在左侧。
<com.google.android.flexbox.FlexboxLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:flexDirection="row"
app:flexWrap="wrap"
app:justifyContent="space_between"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text text"
android:gravity="start"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="end"
android:text="Button"
/>
</com.google.android.flexbox.FlexboxLayout>
那我该怎么办呢?它不需要是FlexBox,我可以使用任何布局,甚至是第三方。
似乎没有办法用Flexbox做到这一点。当你夸大资源(在onCreateView()
或类似的东西)时,我会以编程方式执行此操作。两个视图的父级都是RelativeLayout,当组合的宽度不超过RelativeLayout的宽度时,Button与TextView顶部对齐,当宽度大于此时,对齐到TextView的底部。
无需第三方布局。 ConstraintLayout应该绰绰有余 - 代码中的一个小调整。
您的TextView将具有简单的约束,设置为父布局(开始,顶部,结束)。
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Text text text text text text" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/text" />
</android.support.constraint.ConstraintLayout>
在代码中,只需检查TextView的宽度并将其与父级的宽度进行比较(基本上检查它应该与按钮重叠)。
如果它确实改变了(你必须在代码中执行此操作,但这是原则):
app:layout_constraintTop_toTopOf="@+id/text"
至
app:layout_constraintTop_toBottomOf="@+id/text"
如果您需要动态执行此操作,ConstraintLayout具有简洁的“关键帧动画”功能,可在您更改约束时创建令人敬畏的动画。
在父级中使用justifyContent =“flex_end”并将layout_flexGrow设置为这样适合我的子项。
<com.google.android.flexbox.FlexboxLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="300dp"
android:layout_height="wrap_content"
app:flexDirection="row"
app:flexWrap="wrap"
app:justifyContent="flex_end">
<TextView
android:id="@+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="blah blah"
app:layout_flexGrow="1" />
<TextView
android:id="@+id/textview3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="( . )( . )"
app:layout_flexGrow="0" />
</com.google.android.flexbox.FlexboxLayout>