【问题标题】:LinearLayout, RelativeLayout, etc. margins do not work as expectedLinearLayout、RelativeLayout 等边距不按预期工作
【发布时间】:2011-07-21 17:38:48
【问题描述】:

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

例如,

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


【解决方案1】:

LinearLayout 上的android:padding="40dp" 或Button 上的android:layout_margin="40dp" 会给你想要的效果。内边距定义视图边缘及其内容之间的空间,布局边距定义视图两侧的额外空间。

【讨论】:

  • 边距应将LinearLayout 的边距设置为40dp。奇怪的是它没有按预期工作。
【解决方案2】:

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

边距由父布局管理,因此在本例中为 main FrameLayout。我不知道这是一个功能还是一个错误,但这就是这个布局解释边距的方式。

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

【讨论】:

  • 我记得用 FrameLayout 在 Honeycomb 时间范围内处理边距的方式修复了一些错误,它涉及默认的重力设置。它可能确实是一个错误。 :)
  • 另一种方式是为FrameLayout里面的View设置android:layout_gravity="top|left"。
【解决方案3】:

如果您需要为布局设置边距,只需用另一个线性或相对布局将其包裹起来

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

【讨论】:

  • 这是更好的答案。内边距不一定是您想要的,尤其是当您的布局具有可见背景时。
  • 您应该避免嵌套布局,只是为了给内部布局留出边距。 developer.android.com/training/improving-layouts/…。无论如何,这不是更好的答案。
【解决方案4】:

用另一个布局包裹线性布局是最好的策略。

【讨论】:

    猜你喜欢
    • 2016-10-24
    • 1970-01-01
    • 2012-10-28
    • 2017-08-20
    • 2023-03-25
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多