我正在尝试将具有 4 个相同大小按钮的水平 LinearLayout
转换为 ConstraintLayout
。
问题是,当我在 LinearLayout
中将一个或多个按钮设置为 android:visibility="gone"
时,其余按钮会调整大小以占用整个空间(所有按钮都将大小相同)并且在 ConstraintLayout
中删除了按钮,但仍占用空间。
编辑:根据应用程序状态,将显示不同的按钮。
我需要更改什么才能使 ConstraintLayout
的行为类似于 LinearLayout
?
编辑:我在 ConstraintLayout(约束引用)中发现了一个错误,所以我更新了它和图像(问题仍然存在)。
线性布局
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/b1"
android:text="B1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="50"
/>
<Button
android:id="@+id/b2"
android:text="B2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="50"
android:visibility="gone"
/>
<Button
android:id="@+id/b3"
android:text="B3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="50"
/>
<Button
android:id="@+id/b4"
android:text="B4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="50"
/>
</LinearLayout>
编辑: ConstraintLayout
xml:
<?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">
<Button
android:id="@+id/b1"
android:text="B1"
android:layout_width="0px"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/b2"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_weight="1"
/>
<Button
android:id="@+id/b2"
android:text="B2"
android:layout_width="0px"
android:layout_height="wrap_content"
android:visibility="gone"
app:layout_constraintLeft_toRightOf="@+id/b1"
app:layout_constraintRight_toLeftOf="@+id/b3"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_weight="1"
/>
<Button
android:id="@+id/b3"
android:text="B3"
android:layout_width="0px"
android:layout_height="wrap_content"
app:layout_constraintLeft_toRightOf="@+id/b2"
app:layout_constraintRight_toLeftOf="@+id/b4"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_weight="1"
android:layout_marginTop="0dp"/>
<Button
android:id="@+id/b4"
android:text="B4"
android:layout_width="0px"
android:layout_height="wrap_content"
app:layout_constraintLeft_toRightOf="@+id/b3"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_weight="1"
/>
</android.support.constraint.ConstraintLayout>
最佳答案
您可以轻松地将任何布局转换为 ConstraintLayout
,只需按照以下说明操作即可:
- 转到 Android Studio 布局编辑器中的设计选项卡
- 打开组件树
- 右键单击要转换的 LinearLayout(或其他布局)
- 点击“将 LinearLayout 转换为 ConstraintLayout”
关于android - 将 LinearLayout 转换为 ConstraintLayout 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41411721/