android 布局优化(一),include标签

来源:互联网 发布:mac pro apple care 编辑:程序博客网 时间:2024/05/22 09:01

最近在做项目的时候发现会遇到很多重复的代码。我们在设计android界面的时候一定会遇到多个界面都用到了一个布局文件或布局文件中的标题栏,底部等等。最简单的方法当然是每个界面都copy一份,先不用想效率问题,因为我们根本看不到,就看看这几个界面如果布局的代码都一样的话,我们需要改样式的时候,哪不就要每个界面都需要改动吗?哪有什么方法能够解决这个问题呢?

android提供了include标签,主要就是为了解决layout重用的问题。接下来我就用一个重用标题栏的例子来分别阐述include的具体用法。

1.在layout文件中新建title1.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:background="#ea8010"    >    <Button        android:id="@+id/btn_left"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerVertical="true"        android:layout_marginLeft="15dp"        android:layout_marginTop="9dp"        android:background="@drawable/icon_back" />    <TextView        android:id="@+id/tv_title"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:text="标题"        android:textColor="#fff"        android:textSize="20sp" />    <Button        android:id="@+id/btn_right"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_centerVertical="true"        android:layout_marginRight="15dp"        android:layout_marginTop="9dp"        android:background="@drawable/icon_like" /></RelativeLayout>

2.在需要使用标题栏的多个界面中使用include标签,这里我只使用一个界面。在activity_main布局中引入include标签。

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal" >    <include layout="@layout/title1" /></LinearLayout>

这样调用了include之后,title1文件的内容就被完全嵌入到了include所指定的位置。
这里写图片描述

注:可以include的一些属性,比如:

<include        android:id="@+id/title"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        layout="@layout/title1" />

这时原来layout中的wrap_content就被改成了match_parent属性。
以上就是include的使用过程,是不是方便了许多。直接看效果图:

这里写图片描述

2 0
原创粉丝点击