1:简介
linearlayout顾名思义即是线性布局,只能是垂直布局和水平布局,按照相对位置来排列子元素,如果linearlayout不能包含全部的子元素,那么此时超出的部分将消失。
android:orientation=“vertical”表示此linearlayout的子元素将会是以垂直顺序排列而不管上一子元素所在的行是否横向完全填满,这个类似html中的块状元素;
android:orientation=“horizontal”表示此linearlayout的子元素将会是以垂水平顺序排列而不管上一子元素所在的行是否纵向完全填满,这个类似html中的行内元素;
2:linearlayout中元素左右布局
假设现在存在一个水平线上的两个button需要左右各一个,我们可以想到layout_gravity这个属性,我们可以可以设置它们的在父容器的位置,所以我们的代码如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:layout_width="wrap_content"
android:text="左边的"
android:layout_gravity="left"
android:layout_height="wrap_content"/>
<Button android:layout_width="wrap_content"
android:text="右边的"
android:layout_gravity="right"
android:layout_height="wrap_content"/>
</LinearLayout>
本以为没问题了,但是调试一看。。
怎么回事,这两个按钮怎么还是形影不离啊,原来是left和right只能在LinearLayout android:orientation="vertical"使用,同理,top和down也一样,所以我们修改父类的LinearLayout的orientation,但是这样又存在问题了,vertical每行只能一个了,这不有存在问题了,所以我们可以反向推,如果我们需要button左右的话,而left和right则只能在vertical中使用,而vertical只能每行一个,这样的话一个LinearLayout钟不能同时控制左右两个button,只能每次控制一个,这样我们就想到选择两个LinearLayout分别包含两个button,一个控制左button一个控制右button,并且这两个LinearLayout只能是vertical的,那么此时这两个LinearLayout有必须相邻,所以我们把它们放在同一个水平的LinearLayout中并且占比都是一样的,就是把宽度分成两个部分。代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout android:layout_width="fill_parent"
android:layout_weight="1"
android:orientation="vertical"
android:layout_height="fill_parent">
<Button android:layout_width="wrap_content"
android:text="左边的"
android:layout_gravity="left"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_weight="1"
android:orientation="vertical"
android:layout_height="fill_parent">
<Button android:layout_width="wrap_content"
android:text="右边的"
android:layout_gravity="right"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
效果如下:
这样就做成了左右的效果。
2:linearlayout中元素左中右布局
类似上面的思路,将横向分为三个部分,一个居左,一个居右,一个居中就可以了,其实这样的思路就是将横向分为几份,每份自己组织自己的左右达到布局的效果。
效果如下:
3:linearlayout实现分割线
3.1)利用ImageView、View这些设置背景颜色或者背景图片
3.2) 在Android3.0以后,linearlayout支持直接显示分割线
android:showDividers="end"
android:divider="#00ffcc"