Android布局中的折叠边距问题

19

在Android中是否可以使边距折叠?假设我有一个LinearLayout并添加了三个TextView,每个TextViewandroid:layout_margin都是10dp。我会得到以下结果:

actual result

然而,我希望得到这个结果:

expected result

我知道可以通过为不同的项目设置不同的顶部/底部边距来解决这个问题:
  • 将第一个项目的顶部边距和最后一个项目的底部边距设置为10dp,
  • 将其余的顶部/底部边距设置为5dp,
但这会使设计变得更加复杂(特别是如果TextView是动态创建的)。有没有办法使边距的行为像CSS一样?(有关为什么这是有意义的解释,请参见:What is the point of CSS collapsing margins?
2个回答

16

我通常会这样修复这个问题:简单地将视图的边距(即您的TextView)减半,并将相同数量的填充添加到包含ViewGroup(即您的LinearLayout)中。这样,您就可以在所有项目周围获得均匀的间距。例如:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dip"
    >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:text="I'm a TextView!"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:text="I'm a TextView!"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:text="I'm a TextView!"
        />
</LinearLayout>

2
我很惊讶这仍然是我迄今为止找到的最佳答案。它只对这种情况有效,但在元素高度发生变化的复杂布局中无法使用。 - Zach

0
发布一个解决方案,供未来可能需要的人参考。适用于静态和动态AdapterView,其中列表项是动态的。

示例父容器:

<RecyclerView
     ----
     android:padding_top="10dp"
     android:padding_start="10dp"
     android:padding_end="10dp"
     ---- 
>
</RecyclerView>

填充确保窗口顶部、左侧和右侧的间距。

现在唯一剩下的是两个相邻子项之间的垂直间隙和最后一个子项之后的底部间隙。

示例子项/项目视图:

<RelativeLayout
     ----
     android:margin_bottom="10dp"
     ----
>
     <DynamicChild1 />
     <DynamicChild2 />
</RelativeLayout>

对于这个问题,子视图将只是一个带有底部边距的TextView

这将为您提供与问题中预期的完全相同的输出。


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