Android類參考---Fragment(一)

來源:互聯網
上載者:User

1. 繼承關係

java.lang.Object

|__android.app.Fragment

實現介面:ComponentCallbacks2 View.OnCreateContextMenuListener

引入版本:API Level 11

已知的子類:

DialogFragment、ListFragment、PreferenceFragment、WebViewFragment

2. 類概要

一個Fragment是應用程式的使用者介面或行為的一個片段,它能夠被放置在一個Activity中。通過FragmentManager對象來實現與Fragment對象的互動,能夠通過Activity.getFragmentManager()方法和Fragment.getFragmentManager()方法來擷取FragmentManager對象。

Fragment類有著廣泛的應用,它的核心是代表了一個正在較大的Activity中啟動並執行特俗的操作或介面。Fragment對象跟它所依附的Activity對象是緊密相關的,並且不能被分開使用。儘管Fragment對象定義了它們自己的生命週期,但是這個生命週期要依賴與它所在的Activity:如果該Activity被終止,那麼它內部的Fragment是不能被啟動的;當Activity被銷毀時,它內部的所有Fragment對象都會被銷毀。

所有的Fragment子類都必須包含一個公用的空的構造器。在需要的時候,Framework會經常重新執行個體化Fragment類,在特殊的狀態恢複期間,需要能夠找到這個構造器來執行個體化Fragment類。如果空的構造器無效,那麼在狀態恢複期間會導致運行時異常發生。

較舊的平台

儘管Fragment API是在HONEYCOMB版本中被引入的,但是通過FragmentActivity也能夠在較舊的平台上使用該API。

聲明周期

儘管Fragment對象的生命週期要依附於它所在的Activity對象,但是它也有自己標準的活動周期,它包含了基本的活動周期方法,如onResume(),但是同時也包含了與Activity和UI互動相關的重要方法。

顯示Fragment時(跟使用者互動)要調用的核心的生命週期方法如下:

1. 把Fragment對象跟Activity關聯時,調用onAttach(Activity)方法;

2. Fragment對象的初始建立時,調用onCreate(Bundle)方法;

3. onCreateView(LayoutInflater, ViewGroup, Bundle)方法用於建立和返回跟Fragment關聯的View對象;

4. onActivityCreate(Bundle)方法會告訴Fragment對象,它所依附的Activity對象已經完成了Activity.onCreate()方法的執行;

5. onStart()方法會讓Fragment對象顯示給使用者(在包含該Fragment對象的Activity被啟動後);

6. onResume()會讓Fragment對象跟使用者互動(在包含該Fragment對象的Activity被啟恢複後)。

Fragment對象不再使用時,要反向回調的方法:

1. 因為Fragment對象所依附的Activity對象被掛起,或者在Activity中正在執行一個修改Fragment對象的操作,而導致Fragment對象不再跟使用者互動時,系統會調用Fragment對象的onPause()方法;

2. 因為Fragment對象所依附的Activity對象被終止,或者再Activity中正在執行一個修改Fragment對象的操作,而導致Fragment對象不再顯示給使用者時,系統會調用Fragment對象的onStop()方法。

3. onDestroyView()方法用於清除跟Fragment中的View對象關聯的資源;

4. Fragment對象的狀態被最終清理完成之後,要調用onDestroy()方法;

5. 在Fragment對象不再跟它依附的Activity關聯的時候,onDetach()方法會立即被調用。

 

布局

Fragment對象能夠被用於應用程式的布局,它會讓代碼的模組化更好,並且針對Fragment所啟動並執行螢幕,讓使用者介面的調整更加容易。例如,一個簡單的由項目列表和項目明細表示所組成的程式。

一個Activity的布局XML能夠包含要嵌入到布局內部的Fragment執行個體的<fragment>標籤。例如,下例中在布局中嵌入了一個Fragment對象:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
            android:id="@+id/titles"
            android:layout_width="match_parent" android:layout_height="match_parent" />
</FrameLayout>

以下是布局被安裝到Activity中的通常方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.fragment_layout);
}

依賴ListFragment對象,要顯示列表的標題是相當簡單的。要注意的是,點擊一個清單項目的實現,會依賴當前Activity的布局,它既可以建立一個新的Fragment用於顯示該項目的明細,也可以啟動一個新的Activity用於顯示項目的明細。

public static class TitlesFragment extends ListFragment {
    boolean mDualPane;
    int mCurCheckPosition = 0;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Populate list with our static array of titles.
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));

        // Check to see if we have a frame in which to embed the details
        // fragment directly in the containing UI.
        View detailsFrame = getActivity().findViewById(R.id.details);
        mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

        if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
        }

        if (mDualPane) {
            // In dual-pane mode, the list view highlights the selected item.
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            // Make sure our UI is in the correct state.
            showDetails(mCurCheckPosition);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        showDetails(position);
    }

    /**
     * Helper function to show the details of a selected item, either by
     * displaying a fragment in-place in the current UI, or starting a
     * whole new activity in which it is displayed.
     */
    void showDetails(int index) {
        mCurCheckPosition = index;

        if (mDualPane) {
            // We can display everything in-place with fragments, so update
            // the list to highlight the selected item and show the data.
            getListView().setItemChecked(index, true);

            // Check what fragment is currently shown, replace if needed.
            DetailsFragment details = (DetailsFragment)
                    getFragmentManager().findFragmentById(R.id.details);
            if (details == null || details.getShownIndex() != index) {
                // Make new fragment to show this selection.
                details = DetailsFragment.newInstance(index);

                // Execute a transaction, replacing any existing fragment
                // with this one inside the frame.
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.details, details);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }

        } else {
            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Intent intent = new Intent();
            intent.setClass(getActivity(), DetailsActivity.class);
            intent.putExtra("index", index);
            startActivity(intent);
        }
    }
}

明細Fragment對象只會顯示所選項目的詳細文本字串,它是基於內建在應用中的一個字元數組的索引來擷取的:

public static class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (container == null) {
            // We have different layouts, and in one of them this
            // fragment's containing frame doesn't exist.  The fragment
            // may still be created from its saved state, but there is
            // no reason to try to create its view hierarchy because it
            // won't be displayed.  Note this is not needed -- we could
            // just run the code below, where we would create and return
            // the view hierarchy; it would just never be used.
            return null;
        }

        ScrollView scroller = new ScrollView(getActivity());
        TextView text = new TextView(getActivity());
        int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                4, getActivity().getResources().getDisplayMetrics());
        text.setPadding(padding, padding, padding, padding);
        scroller.addView(text);
        text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
        return scroller;
    }
}

在使用者點擊標題的情況下,在當前的Activity中沒有明細容器,因此標題Fragment的點擊事件代碼會啟動一個新的顯示明細Fragment的Activity:

public static class DetailsActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_LANDSCAPE) {
            // If the screen is now in landscape mode, we can show the
            // dialog in-line with the list so we don't need this activity.
            finish();
            return;
        }

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
        }
    }
}

但是,螢幕可能足夠顯示標題列表和當前所選標題相關的明細。對於在橫向螢幕上這樣的布局,可以被放置在layout-land下面:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
            android:id="@+id/titles" android:layout_weight="1"
            android:layout_width="0px" android:layout_height="match_parent" />

    <FrameLayout android:id="@+id/details" android:layout_weight="1"
            android:layout_width="0px" android:layout_height="match_parent"
            android:background="?android:attr/detailsElementBackground" />

</LinearLayout>

要注意的是,以上代碼是如何調整這種可選的UI流的:標題Fragment對象被嵌入到該Activity內部的明細Fragment對象中,並且如果Fragment對象運行在一個有顯示明細空間的配置環境中,那麼明細Activity會由它自己來完成。

當由於配置的改變而導致Activity所持有的這些Fragment對象重啟的時候,它們新的Fragment執行個體可以使用與之前所使用的布局不同的布局。在這種情況中,之前所有的Fragment對象依然會被執行個體化,並運行在新的執行個體中。但是任何不在跟<fragment>關聯的View對象將不會再被建立,並且重isInLayout()方法中返回false。

在把Fragment的View對象綁定到父容器的時候,<fragment>標籤的屬性被用於控制提供給LayoutParams對象的資訊,它們能夠作為Fragment對象中的onInflate(Activity, AttributeSet, Bundle)方法的參數來解析。

正在執行個體化的Fragment對象必須要有某些類型唯一標識,以便在它的父Activity在銷毀並重建的時候,能夠被重新關聯到之前的執行個體。可以使用以下方法來實現這種關聯:

1. 如果沒有明確的指定,則使用容器的View ID來標識;

2. 使用<fragment>元素的android:tag屬性,給Fragment對象元素提供一個特定的標籤名稱;

3. 使用<fragment>元素的android:id屬性,給Fragment對象的元素提供一個特定的標識。

 


摘自 FireOfStar的專欄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.