LinearLayout*** 线性布局
- LinearLayout 线性布局
- 这个布局会将它所包含的控件在线性方向上一次排列,默认排列方式是横向
- 可以通过代码来指定排列方式
android:orientation=”horizontal”
-android:orientation=”vertical”需要注意的是,如果是横向排列,不能将控件的宽指定为match_parent
这样的话,这一个控件就会将整个水平方向占满。
同样的道理,如果是纵向排列,不能将空间的高指定为match_parent,这样一个控件会将整个纵向方向占满。android:gravity属性,是用于指定文字在控件中的对齐方式。
android:layout_gravity是用于指定控件在布局中的对齐方式
android:layout_gravity="top"
android:layout_gravity="center_vertical"
android:layout_gravity="bottom"
需要注意的是,当布局为横向布局时,我们只能指定垂直方向的排列方向
当布局为纵向布局时,我们只能指定横向的排列方式。
比重 layout_weight
这个属性允许我们使用比例的方式来显示控件,在手机适配方面很有作用
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
你会发现,这里我们将两个控件的宽度都指定为0dp,这样只是一种规范的写法,因为此时的width已经不是由android:layout_width决定,而是由layout_weight决定,我们将TextView指定为2,Button指定为1,表示在水平方向,TextView占 2/3 个父布局的宽度, Button 占 1/3 个父布局的宽度
当然我们也可以这么弄,设置Button的大小为刚刚包裹住内容就好,剩下的空间就交给TextView吧。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>