线性布局,相对布局等边距不按预期工作

25

布局组中的边距似乎无法工作。

例如,

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

应该在四个方向上都显示一个带有40p边距的按钮。但是右侧和底部的边距为80p。

我做错了什么吗? 这是一个bug吗?

一种解决方法是使用重力,但这只适用于均匀的边距。

顺便说一下,有一个类似的问题在这里发布,但还没有得到答案。


尝试将按钮设置为水平居中。 - Zar E Ahmer
4个回答

28
在LinearLayout上使用android:padding="40dp"或在Button上使用android:layout_margin="40dp",将会给您想要的效果。Padding定义了视图边缘和其内容之间的空间,布局边距定义了视图侧面的额外空间。

4
应该通过在所有边缘添加40dp的空白来设置LinearLayout的边距。奇怪的是它没有按预期工作。 - Muhammad Babar

13

问题实际上在于FrameLayout如何解释边距。 setContentView()将您的“主”布局附加到FrameLayout上,后者是视图层次结构的实际根(您可以通过层次结构查看器来查看),并由手机向您提供。

边距由父布局管理,因此在这种情况下是主要的FrameLayout。我不知道它是一个功能还是一个漏洞,但这就是这个布局解释边距的方式。

所以好吧,在我打字的时候,解决方案已经发布了:改用填充。


我记得在Honeycomb时期修复了一些与FrameLayout处理边距的错误,这涉及到默认重力设置。这可能确实是一个错误。 :) - adamp
另一种方法是为FrameLayout中的View设置android:layout_gravity="top|left"。 - VinceStyling

7

如果您需要为布局设置边距,只需将其包装在另一个线性或相对布局中即可。

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

2
这是更好的答案。如果您的布局具有可见背景,则填充并不一定是您想要的。 - Christopher Pickslay
你应该避免仅为内部布局添加边距而嵌套布局。这种方式并不是更好的答案。http://developer.android.com/training/improving-layouts/optimizing-layout.html - Pedro Oliveira

0

使用另一个布局将线性布局包装起来是最佳策略。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接