2012-07-31 83 views
16

Android中的边缘折叠可能会崩溃吗?假设我有一个LinearLayout并添加三个TextView s,每个都有android:layout_margin10dp。我得到以下结果:Android布局中的折叠边距

actual result

不过,我想得到这样的结果:

expected result

我知道我可以通过设置不同的上/下边距解决此不同的项目:

  • 设置第一项的上边距和最后一项的下边距为10dp,
  • 设置耳提面命顶部/底部边距5DP,

但使得设计更加复杂(尤其是如果是动态创建的TextViews)。有什么方法可以使边界像CSS一样运行? (为了解释为什么这是有道理的,请参阅:What is the point of CSS collapsing margins?

回答

14

我通常会自己解决这个问题,就是简单地将View的(即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>