Sheehan Alam
Sheehan Alam

Reputation: 60869

How to space out items in a LinearLayout?

I want to create a toolbar that looks like:

enter image description here

How can I do this in XML? Here is what mine looks like currently:

<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/toolbarLinearLayout" android:background="@color/solid_yellow">
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/replyButton" android:text="Reply"></Button>
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RT" android:id="@+id/rtButton"></Button>
        <Button android:id="@+id/dmButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="DM"></Button>
    </LinearLayout>

Upvotes: 4

Views: 14930

Answers (3)

anjaneya
anjaneya

Reputation: 708

Add android:layout_margin="some value" for item in linearlayout.This worked for me.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

Define your toolbar something like this:

<LinearLayout ...>
    <Button android:id="@+id/replyButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ...
        />
    <View
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        />
    <Button ...
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <!-- etc. -->
</LinearLayout>

All the extra space will be allocated to the transparent views between the buttons.

Upvotes: 3

actionshrimp
actionshrimp

Reputation: 5229

Looks like you might want the padding attribute of the LinearLayout, e.g.

android:padding="5dip"

To get the items to each take up the same amount of space, use layout_weight, e.g.

 <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/toolbarLinearLayout" android:background="@color/solid_yellow">
    <Button android:layout_width="fill_parent" android:layout_weight="1" android:layout_height="wrap_content" android:id="@+id/replyButton" android:text="Reply"></Button>
    <Button android:layout_width="fill_parent" android:layout_weight="1" android:layout_height="wrap_content" android:text="RT" android:id="@+id/rtButton"></Button>
    <Button android:id="@+id/dmButton" android:layout_width="fill_parent" android:layout_weight="1" android:layout_height="wrap_content" android:text="DM"></Button>
</LinearLayout>

As long as all the elements have the same weight they should take up the same space. layout_width="fill_parent" will ensure the whole bar is filled.

Upvotes: 4

Related Questions