初学者在使用android layout时,会遇到view组件定位不准确的问题(我也是),下面就来分析一下常见的layout(LinearLayout和RelativeLayout)的属性和用法。
首先是一个layout的布局,如下:
其中,margin是外边距,规定了该layout的外边距,也就是该layout和其父组件的间隔,常用的相关属性有layout_marginLeft,layout_marginRight,layout_marginTop,layout_marginBottom,分别表示左右上下的外边距。下面是一个小例子:
<LinearLayout
android:orientation="vertical"
android:paddingLeft="50px"
android:paddingTop="100px"
android:paddingRight="150px"
android:paddingBottom="200px"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="200px"
android:layout_marginTop="150px"
android:layout_marginRight="100px"
android:layout_marginBottom="50px"
android:background="#FFFFFF">
</LinearLayout>
</LinearLayout>
</LinearLayout>
这里对于width和height的属性也稍作解释,除了具体的数字定义大小,还可以用两种参数,分别是match_parent和wrap_content,前者强制性的使组件扩展,以填充布局单元内尽可能多的空间。后者将强制性的使视图扩展以显示全部内容。
如图,我构建了3个嵌套的LinearLayout,其中layout1设置了各方向的padding属性,layout2设置各方向的margin属性,结果和预期一致。
除了上述属性控制边距,也可使用比例的方式对画面进行分块,用到的属性是父组件的weightSum和子组件的layout_weight属性,先看例子:
<LinearLayout