android 基本布局
@author lisiwen
@createTIme 2022/04/10
文章中代码链接:https://github.com/NET-lisiwen/UILayoutTest
一个丰富的界面是由很多控件组成的,那么我们才能让各个控件都有条不紊地摆放在界面上,而不是乱糟糟的呢?这就需要借助布局来实现了。布局是一种可用于放置很多控件的容器,它可以按照一定的而规律调整内部控件的位置,从而编写出精美的界面。当然,布局的内部除了放置控件外,也可以放置布局,通过多层布局的嵌套,我们就能够完成一些比较复杂的界面实现,如下图就很好的展示了他们之间的关系
1.LinearLayout
LInearLayout又称线性布局,是一种非常常用的布局。正如它的名字所描述的一样,这个布局会将它所包含的控件在线性方向上依次排列。
既然是线性排列的,肯定就不值有一个方向,可以通过android:orientation
来指定排列的方向,vertical为垂直方向排列,horizontal为水平方向排列。解析来可以体验一下 代码如下所示
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button3"/>
</LinearLayout>
我们在LinearLayout中添加了三个button,每个button长和宽都为wrap_content,并且指定了排列方向为vertical,运行结果如下
接下来我们修改一下排列方向为horizontal排列放下代码如下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
...
</LinearLayout>
这里将android:orientation
属性值改成了horizontal,这就意味着要让LinearLayout中的元素水平方向排列。重新运行结果如下
需要注意的是,如果android:orientation
属性值设置成了horizontal,那么内部元素的宽就不可以设置match_parent,否则一个空降就会将水平方向占满,其他控件就没有空间来展示了,同样道理排列方向是vertical,元素的高也不可以设置成match_parent。
接下来看android:layout_gravity
这个属性,这个和之前介绍控件的时候使用的android:gravity
看起来有点像哈,其实可以理解为android:gravity
为内部元素的对齐方式,android:layout_gravity
为当前控件在父布局中的对齐方式,这两个属性的可选值是差不多的,但是需要注意,当LinearLayout的排列方向是horizontal时,只有垂直方向的对齐方式才会生效,因为毕竟水平方向元素数量还有宽度都不是固定的,因此无法指定水平方向上的对齐方式。同样的道理当对齐方式是vertical时只有水平方向的对齐方式才会生效。修改activity_main.xml的代码,如下所示
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:text="button1"/>
<Button
android:layout_width