本文譯自:http://developer.android.com/training/basics/fragments/creating.html
你可以把一個Fragment想象成一個Activity的模組地區,它有自己的生命週期,接收它自己的輸入事件,並且你可以在Activity運行時添加和刪除它(這有點像一個子Activity,你可以在不同的Activity中重用它們)。本節課向你介紹如何使用支援類庫來擴充Fragment,以便讓你的應用程式能夠在像Android1.6那樣的較舊版本上的相容性。
注意:如果因為一些原因,你決定你的應用程式需要的API層級在11以上,那麼你就不需要使用支援類庫,並且可以使用架構內建的Fragment類和相關的API來代替。要注意的是本課的重點是使用支援類庫中的API,它使用一個特殊的包簽名,並且某些時候API的名稱會比包含在平台內的版本有稍微的不同。
建立Fragment類
要建立一個Fragment,就要繼承Fragment類,然後重寫關鍵的生命週期方法,把你的應用程式邏輯插入其中,這跟Activity類類似。
建立Fragment時的一個不同點是,你必須使用onCreateView()回調來定義布局。實際上,為了獲得一個正在啟動並執行Fragment,這隻是你所需要的唯一的回調方法。例如,下面是一個簡單的指定了自己布局的Fragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class ArticleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.article_view, container, false);
}
}
就像一個Activity,Fragment應該實現其他的生命週期回調方法,從而允許你管理它在Activity中的狀態(添加或刪除),以及Activity在它生命週期狀態間轉換時的狀態。例如,當Activity的onPause()方法被調用時,Activity中的任何Fragment也會接收到對onPause()方法的調用。
有關Fragment的生命週期和有效回調方法,請看Fragments開發指南。
使用XML把一個Fragment添加到一個Activity中
Fragment是可複用的、模組化的UI組件,每個Fragment類的執行個體都必須跟一個父類是FragmentActivity的Activity相關聯。通過在你的Activity布局XML檔案內定義每個Fragment可以完成這種關聯。
注意:FragmentActivity是一個支援類庫中提供的特殊的Activity,它用於處理系統版本是API Level 11以前的Fragment。如果你使用的系統版本最低是API Level 11或更高,那麼就就可以使用常規的Activity。
當螢幕被認為足夠大時,下例布局檔案就會把兩個Fragment添加到一個Activity中(該檔案被放在由large限定的目錄名中)。
res/layout-large/news_articles.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment android:name="com.example.android.fragments.HeadlinesFragment"
android:id="@+id/headlines_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.android.fragments.ArticleFragment"
android:id="@+id/article_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
提示:關於給不同螢幕尺寸建立布局的資訊,請看支援不同的螢幕尺寸。
以下是使用這個布局的Activity:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
}
}
注意:當你通過在布局XML檔案中定義Fragment的方式把Fragment添加給Activity布局時,你不能在運行時刪除該Fragment。如果你打算在使用者互動期間切換Fragment,你就必須在Activity被初次開機時把Fragment添加到Activity中。