注:以下主要内容摘录于《第一行代码——Android》
布局下可以放置布局或控件,以下四种布局常用:
1.LinearLayout
LinearLayout 又称作线性布局,是一种非常常用的布局。
需要注意,如果 LinearLayout 的排列方向是 horizontal,内部的控件就绝对不能将宽度指定为 match_parent,因为这样的话单独一个控件就会将整个水平方向占满,其他的控件就没有可放置的位置了。同样的道理,如果 LinearLayout 的排列方向是 vertical,内部的控件就不能将高度指定为 match_parent。
android:layout_gravity 属性,它和android:gravity 属性看 起来有些相似,android:gravity 是用 于指定文字在控件中的对齐方式而 android:layout_gravity 是用于指定控件在布局中的对齐方式。
<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:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:text="Button 1" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="Button 2" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="Button 3" />
</LinearLayout>
运行上面代码,将显示如下界面。
android:layout_weight。这个属性允许我们使用比例的方式来指定控件的大小,它在手机屏幕的适配性方面可以起到非常重要的作用。
2.RelativeLayout
RelativeLayout 又称作相对布局,也是一种非常常用的布局。和 LinearLayout 的排列规则不同,RelativeLayout 显得更加随意一些,它可以通过相对定位的方式让控件出现在布局的任何位置。每个控件可以相对于父布局进行定位,也可以相对于控件进行 定位。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:text="Button 2" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button2"
android:layout_centerHorizontal="true"
android:text="Button 1" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:text="Button 3" />
</RelativeLayout>
运行上面代码,将显示如下界面。
3.FrameLayout
FrameLayout 相比于前面两种布局就简单太多了,因此它的应用场景也少了很多。这种布局没有任何的定位方式,所有的控件都会摆放在布局的左上角。
4.TableLayout
TableLayout 允许我们使用表格的方式来排列控件,这种布局也不是很常用。
自定义布局