Android 布局中的include标签使用

廉价感情. 提交于 2019-11-27 01:55:22

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_** 属性 不会生效!

总结

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!