LinearLayout,RelativeLayout等边距不能按预期工作

问题描述 投票:21回答:4

组布局中的边距似乎不起作用。

例如,

<?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的边距。

难道我做错了什么?这是一个错误吗?

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

顺便说一句,有一个类似的问题posted here但没有得到回答。

android margin android-linearlayout
4个回答
23
投票

LinearLayout上的android:padding="40dp"或Button上的android:layout_margin="40dp"将为您提供所需的效果。填充定义视图边缘与其内容之间的空间,布局边距定义视图两侧的额外空间。


12
投票

问题实际上是FrameLayout解释边际的方式。 setContentView()将您的“主要”布局附加到FrameLayout,这是视图层次结构的实际根(您可以通过层次结构查看器查看)并通过电话提供给您。

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

好吧,我在输入时已经发布了解决方案:使用填充代替。


6
投票

如果您需要为布局设置边距,只需使用其他线性或相对布局进行包装即可

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

0
投票

用另一种布局包装线性布局是最好的策略。

© www.soinside.com 2019 - 2024. All rights reserved.