Android開發技巧之include避免代碼重複

來源:互聯網
上載者:User

標籤:android   android開發   

在做布局時,經常有些部分是重複的,比如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(轉載請說明出處)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.