布局的使用
在一个丰富的界面中总是由很多个控件组成,这时我们就需要借助布局来对这些控件进行相应调整,从而编写出精美的界面。当然布局出来放置控件外,也可以放置布局,也就是嵌套。通过嵌套我们就可以完成一些相对复杂的界面。
LinearLayout(线性布局)
LinearLayout也就是线性布局,是开发当中非常常用的一种布局。在这个布局当中,所有的控件以及内布都是线性方向上依次排列的。
既然是线性排列,那肯定不仅只有一个方向,它可以水平方向,也可以垂直方向,只需要我们修改LinearLayout的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="horizontal">
<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>
我把orientation属性设置为horizontal,也就是水平排序。
LinearLayout还有一个非常重要的属性,layout_weight权重。他在我们手机屏幕的适配性方面起到了非常重要的作用。下面举一个简单的例子。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="文本内容提示"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="发送"/>
</LinearLayout>
这里是一个水平布局,布局里面有一个EditText和一个Button,宽度都是0dp,设置他们的权重layout_weight都是1,此时EditText和Button就会在水平方向平分父布局的宽度。
如果我们不想他们以1:1的方式平分,我们可以修改他们的权重,比如EditText的layout_weight改为3,button的改为2,此时他们的宽度占比就是3:2。