Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Fragment 入門:概念、生命週期與兩個實例

編輯:關於 Android 程式設計

Android 的畫面一直靠 Activity 撐著,大家都熟得不能再熟。但 Activity 有它的天花板:同一套版面在手機上很好,放到平板上就未必——螢幕一拉寬,控制項間距變得離離落落,視覺反而鬆散。更好的做法是在 Activity 裡嵌幾個「小 Activity」,各自帶自己的版面與邏輯。這就是 Fragment 碎片技術。


一、Fragment 是什麼

Android 從 3.0(API 11)開始引入 Fragment。可以把它想成 Activity 裡的一個模組:有自己的版面、自己的生命週期、單獨處理自己的輸入,並在 Activity 運行時動態加入或移除。設計得當的話,同一個 Fragment 能被多個 Activity 重複使用;當 App 要同時支援平板與手機,用 Fragment 就能輕鬆產出兩套靈活的版面。

二、Fragment 的生命週期

Fragment 必須依附 Activity,所以兩者的生命週期綁得很緊:Activity 暫停,其中所有 Fragment 一起暫停;Activity 進入 stopped,Fragment 也無法啟動;Activity 被銷毀,Fragment 跟著銷毀。反過來說,當 Activity 處於活躍狀態時,你可以獨立控制 Fragment,例如動態加上或移除。

進行 fragment transaction 時,可以把 Fragment 放進 Activity 的回退堆疊,這樣使用者按返回鍵就能逐步回退。


Activity 與 Fragment 生命週期對照

三、實例一:Activity 與 Fragment 通訊

版面檔 activity_main.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1">
    </FrameLayout>
</LinearLayout>

Fragment 本體:

public class MyFragment extends ListFragment {
    String show1[] = {"1.1", "1.2", "1.3", "1.4"};
    String show2[] = {"2.1", "2.2", "2.3", "2.4"};

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        String show[];
        Bundle bundle = getArguments();
        if (bundle == null) {
            show = show1;
        } else {
            show = show2;
            Toast.makeText(getActivity(), (CharSequence) bundle.get("key"), 1).show();
        }
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, show));
    }
}

Activity 用 FragmentTabHost 掛上兩個分頁,並透過 Bundle 傳值:

public class MainActivity extends FragmentActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentTabHost tabHost = (FragmentTabHost) findViewById(R.id.tab);
        tabHost.setup(this, getSupportFragmentManager(), R.id.content);

        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Tab1"),
                MyFragment.class, null);

        Bundle b = new Bundle();
        b.putString("key", "I am tab2");
        tabHost.addTab(tabHost.newTabSpec("tab2")
                        .setIndicator("Tab2", getResources().getDrawable(R.drawable.ic_launcher)),
                MyFragment.class, b);
    }
}

執行結果:

四、實例二:自訂五個分頁的 TabHost

每個碎片各自 inflate 一個版面,例如 fragment_1.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitCenter"
        android:src="@drawable/mm1" />
</LinearLayout>

分頁按鈕的版面 tab_item_view.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:padding="3dp"
        android:src="@drawable/tab_home_btn" />

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="首頁"
        android:textColor="#ffffff"
        android:textSize="10sp" />
</LinearLayout>

主版面 main_tab_layout.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1">

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="0" />
    </FrameLayout>
</LinearLayout>

每個碎片都長得很像,只差 inflate 的版面:

public class FragmentPage1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_1, null);
    }
}

主頁面把「Fragment 類別陣列、圖示陣列、文字陣列」三者對齊索引,迴圈建出所有分頁:

public class MainTabActivity extends FragmentActivity {

    private FragmentTabHost mTabHost;
    private LayoutInflater layoutInflater;

    private Class fragmentArray[] = {
        FragmentPage1.class, FragmentPage2.class, FragmentPage3.class,
        FragmentPage4.class, FragmentPage5.class
    };

    private int mImageViewArray[] = {
        R.drawable.tab_home_btn, R.drawable.tab_message_btn,
        R.drawable.tab_selfinfo_btn, R.drawable.tab_square_btn,
        R.drawable.tab_more_btn
    };

    private String mTextviewArray[] = { "首頁", "消息", "好友", "廣場", "更多" };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_tab_layout);
        initView();
    }

    private void initView() {
        layoutInflater = LayoutInflater.from(this);
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        int count = fragmentArray.length;
        for (int i = 0; i < count; i++) {
            TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i])
                    .setIndicator(getTabItemView(i));
            mTabHost.addTab(tabSpec, fragmentArray[i], null);
            mTabHost.getTabWidget().getChildAt(i)
                    .setBackgroundResource(R.drawable.selector_tab_background);
        }
    }

    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.tab_item_view, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(mImageViewArray[index]);
        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mTextviewArray[index]);
        return view;
    }
}

執行結果:

五、參考資料

android 碎片 Fragment 簡介詳解
Android Fragment 基本介紹
Android Fragment 真正的完全解析(上下)必看

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved