2014年1月6日 星期一

Android 開發 (十一) include

include是幹嘛用的

include 讓我們可以重複使用相同的UI元件,如果需要使用同樣的UI不需要重覆寫在不同的XML檔,只需要寫一遍,然後使用include就可以重覆使用,這樣的好處是方便管理,而且UI有更改時可以一次改所有的頁面。

如何使用include

include_layout.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical" >

  



    <TextView 

        android:id="@+id/txt"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        />

    <ImageView

        android:id="@+id/img"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:background="@drawable/ic_launcher"

        />

</LinearLayout>



首先先寫一份之後會共用的UI,
接著使用 include 在layout這個property中將 include_layout放入

    <include

        android:id="@+id/include"

        layout="@layout/include_layout"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        />



這樣UI就會自行顯示了。


如何取得include內的UI

要取得include內的UI只需要先取得 include 再使用該view去取得想取得的View
如下
View include_layout = (View)findViewById(R.id.include);
TextView txtView = ((TextView)include_layout.findViewById(R.id.txt));
txtView.setText("Include Text");


附上簡單的 sampleCode

沒有留言:

張貼留言