Search code examples
androidandroid-layoutandroid-linearlayout

Best practices for spacing between elements in LinearLayout


I've created a simple LinearLayout with three identical elements:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Hello"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Hello"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Hello"/>
</LinearLayout>

Now I'm going to introduce 8dp space between each pair of elements.

Which solution of the ones below are considered as cleaner?

enter image description here or: enter image description here

or maybe some another?


Solution

  • Try this .

    <?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="wrap_content"
    android:orientation="horizontal">
    
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Hello" />
    
    <android.support.v4.widget.Space
        android:layout_width="8dp"
        android:layout_height="wrap_content" />
    
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Hello" />
    
    <android.support.v4.widget.Space
        android:layout_width="8dp"
        android:layout_height="wrap_content" />
    
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Hello" />
    </LinearLayout>
    

    Add space to your code .

    <android.support.v4.widget.Space
        android:layout_width="8dp"
        android:layout_height="wrap_content" />