Lucas P.
Lucas P.

Reputation: 4532

ConstraintLayout spacing between weighted Views?

I am trying to build an Android UI where I need 7 boxes with the days of the week. In order to do this, I decided to go with a ConstraintLayout in order to be able to auto resize my views on any screen.

I created a chain between all 7 views with the with the "spread_inside" attribute, with worked but since I had my views' widths set to wrap_content, due to the nature of TextViews the views did not have equal widths. So I tried making them have equal widths by setting all of 7 views' widths to 0dp. This works but leaves no space between the views. Is there a way to add some spacing between these 7 views? Or is there another way of achieving the "equal widths" to all 7 views while keeping the auto-resizing ability on any screen? Is this even possible with ConstraintLayout or should I keep using LinearLayout for this kind of things? (as seen in the last screenshot)

I want my views to shrink when the screen is small and to expand up to a level when the screen is big. Please see the screenshots below of how it looks now. I want to add an 8dp padding between each view (on a LinearLayout I achieve this by adding a transparent divider on the layout with 8dp width, as in the last screenshot)

On a large screen

On a small screen

On a very large screen

How it should look, achieved using LinearLayout

How it should look, achieved using LinearLayout

Upvotes: 2

Views: 1967

Answers (1)

lelloman
lelloman

Reputation: 14173

if you want them to be all the same width you don't even need spread_inside, just set the width to 0dp and then add margins to the views. for example:

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

keep in mind that space between views will be the sum of 2 margins, first and last view will have only 1 margin space, so you need to set them accordingly (like 4dp for margins between views and 8dp for first and last margin)

Upvotes: 3

Related Questions