【问题标题】:Collapsing margins in Android layouts在 Android 布局中折叠边距
【发布时间】:2012-07-28 22:38:21
【问题描述】:

是否有可能在 Android 中使边距崩溃?假设我有一个LinearLayout 并添加三个TextViews,每个android:layout_margin10dp。我得到以下结果:

但是,我想得到这个结果:

我知道我可以通过为不同的项目设置不同的顶部/底部边距来解决此问题:

  • 将第一项的上边距和最后一项的下边距设置为10dp,
  • 将剩余的顶部/底部边距设置为 5dp,

但这会使设计更加复杂(特别是如果 TextView 是动态创建的)。有没有办法让边距表现得像 CSS 中的一样? (有关为什么这是有意义的解释,请参阅:What is the point of CSS collapsing margins?

【问题讨论】:

    标签: android android-layout margin collapse


    【解决方案1】:

    我通常自己解决此问题的方法是将视图(即您的 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】:

    为将来可能需要此解决方案的人发布解决方案。适用于静态以及 列表项是动态的 AdapterView

    父容器示例:

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

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

    现在只剩下两个连续孩子之间的垂直间隙和最后一个孩子之后的底部间隙。

    子/项目视图示例:

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

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

    这将为您提供问题中预期的确切输出。

    【讨论】:

      猜你喜欢
      • 2010-09-11
      • 2011-02-09
      • 1970-01-01
      • 2016-12-23
      相关资源
      最近更新 更多