Fragment 學習小結

參考 : http://developer.android.com/guide/components/fragments.html

一 概述

Android 3.0(API level 11)加入,爲了使界面更靈活,可複用,動態生成。

二 要點:

  • 必須嵌入在Activity中,生命週期受Activity影響
  • 當在Activity中添加Fragment時,實際是在加入到ViewGroup中。(可直接用)
  • 成爲Activity的一部分,不一定要Layout,可以做一些不需要看見的工作。

三 使用方法

1. 必須實現的方法

  • onCreate() : 必要的初始化
  • onCreateView() :創建視圖
  • onPause() : 保存數據

2. 基本的fragment類型

  • DialogFragment
  • ListFragment
  • PreferenceFragment

3. 添加Fragment到Activity

3.1 帶界面

  • 在Activity的layout中聲明:
<?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>
  • 在代碼中動態添加:
    注意:需要在Activity的佈局中有一塊空間給fragment
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

3.2 不帶界面

修改如下方法即可:

add(Fragment, String)

設置Tag 來給其提供唯一標識(比id好)

使用方法:findFragmentByTag()

4. 管理Fragments

通過FragmentManager,FragmentTransaction
- add()
- remove()
- replace()

commit()之前,可以setTransition(),使Fragment 變化帶有動畫效果。

5. 替換Fragment的事項。

  • 貌似只是能替換有界面的,並且沒有銷燬它。
  • 不帶界面的fragment即使替換也會一直工作,直到done。

四 與Activity交互

常用方法

  • getActivity();
  • ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);或者用findFragmentByTag()

創建回調函數

public static class FragmentA extends ListFragment {
    ...
    // Container Activity must implement this interface
    public interface OnArticleSelectedListener {
        public void onArticleSelected(Uri articleUri);
    }
    ...
}
public static class FragmentA extends ListFragment {
    OnArticleSelectedListener mListener;
    ...
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnArticleSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
        }
    }
    ...
}

以上是結合官網,歸納的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章