优雅的设计好你的布局-----箴言-----
内容简介:
在实际开发中,经常需要将控件进行水平平均分配,本篇介绍用LinearLayout来实现水平平均。
下面是一个典型的布局文件:
(1)水平平分,在顶部显示:
默认情况下,Layout是在父的layout的顶部。
效果图1:
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="左"></Button>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="中"></Button>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="右"></Button>
</LinearLayout>
(2)水平平分,在竖直居中显示:
只需要在layout中加上android:gravity="center_vertical",即可。
效果图2:
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="左"></Button>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="中"></Button>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="右"></Button>
</LinearLayout>
(3)水平平分,在竖直在底部显示:
只需要在layout中加上android:gravity="center_vertical",即可。
效果图如下:
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="左"></Button>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="中"></Button>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="右"></Button>
</LinearLayout>
说明:
android:orientation:水平还是垂直。
android:gravity:在布局中的顶部,居中,还是底部显示。
android:layout_width:控件宽度。
android:layout_height:控件高度。
android:layout_weight:控件所占权重,例如,3个全是1,说明三个控件的权重是一样的,就实现了平均分配。