前陣用viewpaper+fragment作滑動引導,查閱了下網上的資料,發如今有兩種作法,一個是自建類直接繼承Activity另外一種是繼承FragmentActivity,非常迷惑,在查了些google的官方文檔和StackOverflow以後有了些理解,在此坐下記錄。下面的英文說明取自Stackoverflow,我的感受解釋的很清楚。html
A
Fragment
is a section of anActivity
, 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 anActivity
.android
Fragments
are not part of the API prior to HoneyComb (3.0). If you want to useFragments
in an app targeting a platform version prior to HoneyComb, you need to add the Support Package to your project and use theFragmentActivity
to hold yourFragments
. TheFragmentActivity
class has an API for dealing withFragments
, whereas theActivity
class, prior to HoneyComb, doesn't.webIf your project is targeting HoneyComb or newer only, you should use
Activity
and notFragmentActivity
to hold yourFragments
.apiSome details:app
Use
android.app.Fragment
withActivity
. Useandroid.support.v4.app.Fragment
withFragmentActivity
. Don't add the support packageFragment
to anActivity
as it will cause an Exception to be thrown.ideA thing to be careful with:
FragmentManager
andLoaderManager
have separate support versions for FragmentActivity:佈局If you are using a
Fragment
in anActivity
(HoneyComb and up), callui
getFragmentManager()
to getandroid.app.FragmentManager
getLoaderManager()
to getandroid.app.LoaderManager
if you are using a
Fragment
in aFragmentActivity
(pre-HoneyComb), call:this
getSupportFragmentManager()
to getandroid.support.v4.app.FragmentManager
.getSupportLoaderManager()
to getandroid.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 theActivity
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()