首先给大家介绍一下LinearLayout是干嘛用的!
1、概念
LinearLayout线性布局会将其中包含的控件一个接一个进行排列,可以进行横排也可以竖排!
2、常用属性:
1)设置排列方向:
Xml属性:
1:android:orientation
水平排列:horizontal
垂直排列:vertical
2)设置组件的对齐方式
Xml属性:
1:android:gravity
中央:center
左:left
右:right
也可以用|隔开来设置它的位置
编写左上左下右上右下中央的实现思路
第一步:新建5个Button控件
第二步:将左上与右上两个按钮用一个LinearLayout框起来
将中央按钮用一个LinearLayout框起来
将左下与右下两个按钮用一个LinearLayout框起来
将这三个的layout_width都设置为match_parent
第三步:将右上单个按钮和右下单个按钮分别用LinearLayout框起来
第四步:将右上和右下外围的LinearLayout设置它的比重layout_weight为1,并且设置它的对齐方式gravity为right靠右
第五步:设置中央的layout_weight为1,设置中央的gravity为center
第六步:检查最外围的父LinearLayout的orientation是否为vertical,如果是horizontal的话,请改为vertical
代码片段:<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="左上"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="右上"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="中间"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="左下"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="右下"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
然后效果就出来了: