Android 布局中的include标签使用

来源:互联网 发布:虚拟桌面软件 编辑:程序博客网 时间:2024/04/29 08:24

Android 布局中的include标签使用

最近在布局时,有好多页面都是有共同特点的,比如标题:一个同样的样式!

如下图所示:
这里写图片描述

如果给每个页面都单独的写一个标题的布局那就太麻烦了,如果能写一个标题布局,其它页面重用该多好!
这个时候,<include> 就隆重登场了!

写一个标题的布局 title.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:background="@drawable/navigation_bar"    >    <ImageView        android:id="@+id/img_backward"        android:layout_alignParentLeft="true"        android:layout_centerVertical="true"        android:layout_marginLeft="25dp"        android:layout_gravity="center"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:src="@drawable/backward"        />    <TextView        android:id="@+id/tv_title"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textSize="20sp"        android:gravity="center"        android:layout_centerInParent="true"        android:layout_gravity="center"        android:textColor="@color/white"        android:text="@string/tiltename"        /></RelativeLayout>

在其它几个类似的页面<include> 上面的title.xml 即可:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <!-- 标题 -->    <include        android:id="@+id/title_res"        layout="@layout/title"        />    <!-- 界面内容 -->    <FrameLayout        android:id="@+id/app_content"        android:layout_width="match_parent"        android:layout_height="match_parent"        /></LinearLayout>

需要注意的是,在Google官方文档关于<include ...>最后有一句话:

However, if you want to override layout attributes using the tag, you must override both android:layout_height and android:layout_width in order for other layout attributes to take effect.

意思为:

如果想在 <include ...> 标签中使用 layout_** 属性,那么必须得在include 中包含 android:layout_heightandroid:layout_width,否则其它layout_** 属性 不会生效!

总结

总之, 标签是为了复用已经存在的布局,不需要再写冗余的代码!————复用布局

1 0
原创粉丝点击