星期一, 11月 07, 2011

Fragment (五)

Android應用程式學習筆記

Adding a fragment to an activity

通常,fragment會貢獻一部份使用者介面在寄主activity,有兩種方式你可以將fragment增加到activity佈局上。
  • Declare the fragment inside the activity's layout file
    在此方法中,你可以設定fragment的屬性,以下舉例在activity的layout中增加兩個fragment。

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <fragment android:name="com.example.news.ArticleListFragment"
                android:id="@+id/list"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="match_parent" />
        <fragment android:name="com.example.news.ArticleReaderFragment"
                android:id="@+id/viewer"
                android:layout_weight="2"
                android:layout_width="0dp"
                android:layout_height="match_parent" />
    </LinearLayout>

    在<fragment>標籤範圍中的android:name屬性具體指定了在layout中實體化的Fragment類。
    當系統建立此activity布局時,它實體化佈局中的每個fragment並且呼叫每個fragment的onCreateView()方法去取得每個fragment的布局,系統將onCreateView()回傳的View直接插入<fragment>標籤的位置。
  • Or programmatically add the fragment to an existing ViewGroup
    在activity運行的任何時間,你可以增加fragment到你的activity布局,你需要指定fragment該置於哪個ViewGroup。在activity布局處理fragment的相關工作(比如新增、移除或是取代fragment),你必須使用FragmentTransaction,你可以從你的activity取得FragmentTransaction實例,如下。
  • FragmentManager fragmentManager = getFragmentManager()
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    你接著可以利用add()方法增加fragment,指定新增的fragment和插入fragment的View。
    ExampleFragment fragment = new ExampleFragment();
    fragmentTransaction.add(R.id.fragment_container, fragment);
    fragmentTransaction.commit();
    第一個傳入add()方法是fragment要置入的ViewGroup,由ID來表示,第二個參數是要置入ViewGroup的fragment。一旦你已在FragmentTransaction做了你的改變就必須呼叫commit()方法。

沒有留言:

張貼留言