3

我想知道在Android中是否有任何方法可以在使用ConstraintLayout时设置两个视图之间的最大间距Chains。我知道使用margin属性就像两个视图之间的最小间距一样,但我不知道如何设置最大间距。

例如,我如何通过以下布局 xml(最大间距 = 20dp)来实现这一点?

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/left_view"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="#FF0000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/right_view"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintHorizontal_chainStyle="spread" />

    <View
        android:id="@+id/right_view"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="#00FF00"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/left_view"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</android.support.constraint.ConstraintLayout>
4

2 回答 2

2

使用 设置垂直或水平间距<Space>。关键是将宽度或高度设置0dp为元素之间的最大间距,或固定间距 ( 20dp) 的任何值:

<Space
    android:layout_width="0dp"
    android:layout_height="1dp"/>
于 2019-08-14T11:25:36.630 回答
1

如果你想设置自定义间距(最大 20dp),那么你应该使用这个:

app:layout_constraintHorizontal_chainStyle="packed"

然后,您可以使用边距添加视图之间的间距,使其成为它们之间的最大间距。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">

    <View
        android:id="@+id/left_view"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginEnd="10dp"
        android:background="#FF0000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@+id/right_view"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/right_view"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginStart="10dp"
        android:background="#00FF00"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/left_view"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
于 2019-08-14T10:57:36.217 回答