开发者

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

开发者 https://www.devze.com 2023-02-19 22:05 出处:网络
Margins in group开发者_Python百科 layouts do not seem to work. For example, <?xml version=\"1.0\" encoding=\"utf-8\"?>

Margins in group开发者_Python百科 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.


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.


The problem is actually the way FrameLayout interprets margins. setContentView() attaches your "main" layout to a FrameLayout, which is the actual root of the view hierarchy (you can see that with Hierarchy Viewer) and is offered to you by the phone.

Margins are managed by the parent layout, so in this case that main FrameLayout. I don't know if it's a feature or a bug, but that's how this layout interprets margins.

So well, the solution was already posted while I was typing: use padding instead.


if you need set margin for a layout, simply wrap it with another linear or relative layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

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

</LinearLayout>


Wrapping the Linear Layout with another layout is the best strategy.

0

精彩评论

暂无评论...
验证码 换一张
取 消