线性布局简述
布局的方向
在LinearLayout元素中添加android:orientation特性,将值设置为horizontal即表示行,设置为vertical即表示列,在运行时也可以改变方向,需要通过LinearLayout来调用setOrientation(),并传入HORIZONTAL或VERTICAL参数。如下代码所示
orientation.setOrientation(LinearLayout.HORIZONTAL)
填充模型
位于LinearLayout中所有部件都必须指定android:layout_width和android:layout_height,这两个特性的值可能有3种形式:
①具体的大小,如12px
②“wrap_content”(即包含内容),表示部件应该保持其本来大小,万一太大,android将自动换行,以便部件适应屏幕空间
③“fill_parent”(即填充父元素)表示在处理完所有其他部件之后,当前部件应该填满包含他的容器的所有可用空间
代码如下:
android:layout_width="fill_parent"
android:layout_height="wrap_content"
权重
将布局中部件的android:layout_weight值设置为想要的比例
gravity
在部件中设置android:layout_gravity特性可以告诉部件及其容器如何在屏幕中对齐部件。
对于一列部件,常见的重力值有:left、center_horizontal和right,分别表示左对齐、水平居中对齐和右对齐。
对于一行部件,默认的对齐方式时让他们包含的文本沿基线对齐。将重力值设置为center_vertical可以将部件与相应行的垂直中点对齐。
内边距
如果想加大部件之间的距离,可以使用android:padding特性。内边距指的是部件外层边界与部件内容的边界之间的距离。可以使用android:paddingRight、android:paddingLeft、android:paddingTop、android:paddingBottom
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" //以行的方式布局>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"//设置权重
android:background="#ffffff"
android:gravity="center" //将Text居中
android:text="@string/A"
android:textSize="15sp"></TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:background="#ffaa88"
android:gravity="center"
android:text="@string/B"
android:textSize="15sp"></TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:background="#ff00ff"
android:gravity="center"
android:text="@string/C"
android:textSize="15sp"></TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="4"
android:background="#eec900"
android:gravity="center"
android:text="@string/D"
android:textSize="15sp"></TextView>
</LinearLayout>
</android.support.constraint.ConstraintLayout>