线性布局是我们在android开发中经常会使用的布局控件,今天我们一起来总结一下在线性布局使用的过程中的注意事项。我只是搬运工,知识大多来自于网络。
最常用的属性是:
<!--
android:orientation="horizontal"
android:gravity="center"
orientation 方向 vertical 表示垂直方向 horizontal表示水平方向
gravity 设置所有子控件(作为一个整体)相对于父布局的位置
-->
(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"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="45dp"
android:layout_weight="1"
android:background="#55ff0000"
android:gravity="center"
android:text="aaaaaaaaaaaaaaaa"/>
<TextView
android:layout_width="0dp"
android:layout_height="45dp"
android:layout_weight="1"
android:background="#5500ff00"
android:gravity="center"
android:text="b"/>
<TextView
android:layout_width="0dp"
android:layout_height="45dp"
android:layout_weight="1"
android:background="#550000ff"
android:gravity="center"
android:text="c"/>
</LinearLayout>
这段代码的效果图是:
很明显,第一个textview的对齐方式不是我们想要的,出现这种现象的原因是LinearLayout默认子控件按照基准线对齐,所以我们需要在LinearLayout中添加一个属性就即可解决:android:baselineAligned="false" 使得子控件不按照基线对齐。
(2)layout_weight属性使用要注意什么?
android官方推荐我们在使用layout_weight属性来按照比例分配空间的时候,该方向上的值(宽度或者高度)最好设置为0dp,原因是:在为每一个子控件分配空间的时候,首先按照控件声明的尺寸进行分配,然后再将剩下的尺寸按照比例进行分配;所以如果我们没有将该方向上的尺寸值设置为0dp,就会对我们按照比例分配空间产生干扰,比如说下面的代码:
<?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:orientation="horizontal"
android:baselineAligned="false">
<TextView
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_weight="1"
android:background="#55ff0000"
android:gravity="center"
android:text="aaaaaaaaaaaaaaaa"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_weight="1"
android:background="#5500ff00"
android:gravity="center"
android:text="b"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_weight="1"
android:background="#550000ff"
android:gravity="center"
android:text="c"/>
</LinearLayout>
这段代码的效果是:
可以看出并没有按照比例进行分配,所以我们需要将水平方向上的宽度值全都设置为0dp,才能达到效果。
(3)weightSum属性得使用
如果布局中只有一个控件,并且我只想让它占据1/2的宽度,这个时候就可以利用LinearLayout的weightSum属性,来看看这个例子:
<?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:orientation="horizontal"
android:weightSum="2">
<TextView
android:layout_width="0dp"
android:layout_height="45dp"
android:layout_weight="1"
android:background="#55ff0000"
android:gravity="center"
android:text="aaaaaaaaaaaaaaaa"/>
</LinearLayout>
效果如图:
(4)重要的总结
layout开头的属性都是交给父容器,没有layout开头的都是本身的属性。