LinearLayout, RelativeLayout, etc. margins do not work as expected

Matt picture Matt · Mar 24, 2011 · Viewed 45.1k times · Source

Margins in group layouts do not seem to work.

For example,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_margin="40dip"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="I'm a button" />

</LinearLayout>

should display a button with 40p margins on all sides. However, it has 80p margins on the right and bottom.

Am I doing something wrong? Is this a bug?

A workaround would be to use gravity, but this only works with even margins.

BTW, there is a similar question posted here but has not been answered.

Answer

Robby Pond picture Robby Pond · Mar 24, 2011

android:padding="40dp" on the LinearLayout or android:layout_margin="40dp" on the Button will give you the effect you want. Padding defines the space between a views edges and its content, layout margin defines extra space on the sides of a view.