现在的位置: 首页 > 综合 > 正文

Android开发技巧之include避免代码重复

2014年08月17日 ⁄ 综合 ⁄ 共 1726字 ⁄ 字号 评论关闭

在做布局时,经常有些部分是重复的,比如title或者foot的地方,最简单的办法当然是直接复制过去,

这里介绍include的用法,有过c++或者c经验的同学一看就明白了,就是把另一个布局包含进来.

先看下实现的效果:

里面上下各有两个文字布局,是用include包含进去的,直接看代码

activity_main.xml:

<RelativeLayout 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" >

    <include
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="30dp"
        layout="@layout/header" />

    <ViewStub
        android:id="@+id/pic_stub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:inflatedId="@+id/pic_view_id_after_inflate"
        android:layout="@layout/pic_view" />


    <include layout="@layout/footer" />

</RelativeLayout>

很清楚的两个include,至于中间的viewstub,在下一篇博客里讲解

地址:http://blog.csdn.net/jason0539/article/details/26132267 

 

代码里我用了两个include,

第一个比较复杂,设置了属性,让它在布局顶部

第二个比较简洁,属性都没有设置,但是位置却很正确,在布局的底部,

这样的目的是为了展示include属性的两种设置方式,可以在include标签里设置,也可以在所要引用的布局里面设置

所包含的两个布局文件如下:

header.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:gravity="center_horizontal"
    android:text="Header Without Properties!" >

</TextView>

在这里面的宽度高度都设置为0了,目的就是要在布局中通过include标签设置它的布局

 

footer.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="30dp"
    android:gravity="center_horizontal"
    android:text="With Properties!" />

这个的属性设置的很完整,所以在布局中include标签里就什么都没设置,直接引用就行了,

 

两种方法效果相同,看个人喜好来用.

作者:jason0539

微博:http://weibo.com/2553717707

博客:http://blog.csdn.net/jason0539(转载请说明出处)

抱歉!评论已关闭.