Fragment與FragmentActivity的關係

前陣用viewpaper+fragment作滑動引導,查閱了下網上的資料,發如今有兩種作法,一個是自建類直接繼承Activity另外一種是繼承FragmentActivity,非常迷惑,在查了些google的官方文檔和StackOverflow以後有了些理解,在此坐下記錄。下面的英文說明取自Stackoverflow,我的感受解釋的很清楚。html

A Fragment is a section of an Activity, which has:java

  • its own lifecycle
  • receives its own input events
  • can be added or removed while the Activity is running.

A Fragment must always be embedded in an Activity.android

Fragments are not part of the API prior to HoneyComb (3.0). If you want to use Fragments in an app targeting a platform version prior to HoneyComb, you need to add the Support Package to your project and use the FragmentActivity to hold your Fragments. The FragmentActivity class has an API for dealing with Fragments, whereas the Activity class, prior to HoneyComb, doesn't.web

If your project is targeting HoneyComb or newer only, you should use Activity and notFragmentActivity to hold your Fragments.api

Some details:app

Use android.app.Fragment with Activity. Use android.support.v4.app.Fragment withFragmentActivity. Don't add the support package Fragment to an Activity as it will cause an Exception to be thrown.ide

A thing to be careful with: FragmentManager and LoaderManager have separate support versions for FragmentActivity:佈局

If you are using a Fragment in an Activity (HoneyComb and up), callui

  • getFragmentManager() to get android.app.FragmentManager
  • getLoaderManager() to get android.app.LoaderManager

if you are using a Fragment in a FragmentActivity (pre-HoneyComb), call:this

  • getSupportFragmentManager() to get android.support.v4.app.FragmentManager.
  • getSupportLoaderManager() to get android.support.v4.app.LoaderManager

so, dont do

myFragmentActivity.getLoaderManager()//don't do this, do myFragmentActivity.getSupportLoaderManager()

or

android.app.FragmentManager fm = myFragmentActivity.getSupportFragmentManager()//don't do this, do android.support.v4.app.FragmentManager fm = myFragmentActivity.getSupportFragmentManager()

Also useful to know is that while a fragment has to be embedded in an Activity it doesn't have to be part of the Activity layout. It can be used as an invisible worker for the activity, with no UI of its own.

總結來講就是標紅記錄的說明:

一、fragmentactivity 繼承自activity,用來解決android3.0 以前沒有fragment的api,因此在使用的時候須要導入support包,同時繼承fragmentActivity,這樣在activity中就能嵌入fragment來實現你想要的佈局效果。

二、固然3.0以後你就能夠直接繼承自Activity,而且在其中嵌入使用fragment了。

三、得到Manager的方式也不一樣

3.0如下:getSupportFragmentManager()

3.0以上:getFragmentManager()

相關文章
相關標籤/搜索