当前位置: 移动互联网学院 > Android开发 > LinearLayout中margin属性小结
LinearLayout中margin属性小结 时间:2017-08-16     来源:移动互联网学院

以线性布局中采用的horizontal为例, 总结margin属性的使用。

总结1: 

此时我们水平放置三个Button.其中给第二个 Button2设置android:layout_marginRight="50dip" ,请注意此时并不是说明Button2距离父控件的右边距离为50dip,而是说明Button2距离它右边的同级子控件的距离为50dip。(只有其右边没有同级子控件的时候,设置layout_marginRight 才是相对于父控件的右边而言的),

这也就是说当放置Button3的时候是从距离Button2右边50dip的距离开始的。

总结2: 

button1设置了android:layout_marginRight="10dip" 

button2设置了android:layout_marginLeft="20dip" 

那么两者的实际间距为10+20=30; 

总结3: 

后一个子控件存在这么一种情况: 

布局代码若设置button3中 android:layout_marginRight="60dip" 

那么button3会被挤变形。

从以下几种情况: 

(1)若只给button3设置android:layout_marginLeft="10dip" 

   android:layout_marginRight="10dip",则正常显示 

(2)若只给button3设置android:layout_marginLeft="80dip" 

   那么button会变形 

(3)若只给button3设置android:layout_marginLeft="80dip" 

  android:layout_marginRight="10dip"那么button3会更加 

  严重变形,且距离右边的边框有10dip的距离 

  可总结出: 

  在水平线性布局中后一个子控件的右边缘距离父控件右边的距离为A 

  若给该控件设置android:layout_marginRight="B" 

  第一种情况:A>B时控件不会变形 

  第二种情况:A<B时.控件会被压缩,并且是从右往左压缩(即控件的左基准线不会动摇)迫使距离父控件的距离为B. 

  线性垂直布局与此类似。

horizontal.xml如下:

<LinearLayout>

    xmlns:android="//schemas.android.com/apk/res/android"  

    android:layout_width="match_parent"  

    android:layout_height="match_parent"  

    android:orientation="horizontal"  

    >  

    <Button  

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content"  

        android:layout_marginLeft="20dip"  

        android:layout_marginRight="10dip"  

        android:text="button1" />  

    <Button  

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content"  

        android:layout_marginLeft="10dip"  

        android:layout_marginRight="20dip"  

        android:text="button2" />  

    <Button  

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content"  

        android:layout_marginLeft="10dip"  

        android:layout_marginRight="10dip"  

        android:text="button3" />  

</LinearLayout>