ConstraintLayout加权视图之间的间距?

时间:2017-12-14 21:15:34

标签: android android-layout layout android-constraintlayout

我正在尝试构建一个Android UI,我需要7个方框,包含一周的日期。为了做到这一点,我决定使用ConstraintLayout,以便能够在任何屏幕上自动调整我的视图大小。

我使用带有“spread_inside”属性的所有7个视图之间创建了一个链,但由于我将视图的宽度设置为wrap_content,由于TextViews的性质,视图没有相同的宽度。所以我尝试通过将所有7个视图的宽度设置为0dp来使它们具有相等的宽度。这有效,但视图之间没有空间。有没有办法在这7个视图之间添加一些间距?或者是否有另一种方法可以在所有7个视图中实现“相等宽度”,同时在任何屏幕上保持自动调整大小的能力?这甚至可以使用ConstraintLayout,还是应该继续使用LinearLayout来做这类事情? (如上一张截图所示)

我希望我的视图在屏幕较小时缩小,并在屏幕较大时扩展到某个级别。请参阅下面的屏幕截图,了解它现在的样子。我想在每个视图之间添加一个8dp填充(在LinearLayout上我通过在布局上添加8dp宽度的透明分隔符来实现这一点,如上一屏幕截图所示)

On a large screen

On a small screen

On a very large screen

How it should look, achieved using LinearLayout

使用LinearLayout

实现的外观

1 个答案:

答案 0 :(得分:2)

如果您希望它们的宽度相同,甚至不需要spread_inside,只需将宽度设置为0dp,然后为视图添加边距即可。例如:

<?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">

    <View
        android:id="@+id/view1"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_marginRight="4dp"
        android:layout_marginLeft="8dp"
        android:background="#ffff0000"
        app:layout_constraintEnd_toStartOf="@+id/view2"
        app:layout_constraintStart_toStartOf="parent"/>

    <View
        android:id="@+id/view2"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="4dp"
        android:background="#ff00ff00"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/view1"/>

</android.support.constraint.ConstraintLayout>

请记住,视图之间的间距将是2个边距的总和,第一个和最后一个视图将只有1个边距空间,因此您需要相应地设置它们(如4dp表示视图之间的边距,8dp表示第一个和最后一个边距) )