引入布局
经过前面两节的学习,我想创建一个标题栏布局已经不是什么困难的事情了,
只需要加入两个 Button和一个 TextView,然后在布局中摆放好就可以了。可是这样做却存
在着一个问题,一般我们的程序中可能有很多个活动都需要这样的标题栏,如果在每个活动
的布局中都编写一遍同样的标题栏代码,明显就会导致代码的大量重复。这个时候我们就可
以使用引入布局的方式来解决这个问题,新建一个布局
title.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/title_bg" > <Button android:id="@+id/title_back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="5dip" android:background="@drawable/back_bg" android:text="Back" android:textColor="#fff" /> <TextView android:id="@+id/title_text" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1" android:gravity="center" android:text="Title Text" android:textColor="#fff" android:textSize="24sp" /> <Button android:id="@+id/title_edit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="5dip" android:background="@drawable/edit_bg" android:text="Edit" android:textColor="#fff" /> </LinearLayout>
在LinearLayout中分别加入了两个Button和一个TextView,左边的Button
可用于返回,右边的 Button可用于编辑,中间的 TextView则可以显示一段标题文本。上面
的代码中大多数的属性都已经是见过的,下面我来说明一下几个之前没有讲过的属性。
android:background用于为布局或控件指定一个背景,可以使用颜色或图片来进行填充,这
里我提前准备好了三张图片,title_bg.png、back_bg.png和 edit_bg.png,分别用于作为标题栏、
返回按钮和编辑按钮的背景。另外在两个Button中我们都使用了android:layout_margin这个属
性,它可以指定控件在上下左右方向上偏移的距离,当然也可以使用android:layout_marginLeft
或 android:layout_marginTop等属性来单独指定控件在某个方向上偏移的距离。
现在标题栏布局已经编写完成了,剩下的就是如何在程序中使用这个标题栏了,修改 activity_main.xml中的代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <include layout="@layout/title" /> </LinearLayout>
没错!我们只需要通过一行 include语句将标题栏布局引入进来就可以了
就是这么简单!!!
这是效果图


浙公网安备 33010602011771号