Fragment与FragmentActivity的关系
前陣用viewpaper+fragment做滑動引導,查閱了下網上的資料,發現在有兩種做法,一個是自建類直接繼承Activity另一種是繼承FragmentActivity,很是迷惑,在查了些google的官方文檔和StackOverflow之后有了些理解,在此坐下記錄。下面的英文說明取自Stackoverflow,個人感覺解釋的很清楚。
A?Fragment?is a section of an?Activity, which has:
- 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.
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.
If your project is targeting HoneyComb or newer only, you should use?Activity?and notFragmentActivity?to hold your?Fragments.
Some details:
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.
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), call
- getFragmentManager()?to get?android.app.FragmentManager
- getLoaderManager()?to get?android.app.LoaderManager
if you are using a?Fragment?in a?FragmentActivity?(pre-HoneyComb), call:
- getSupportFragmentManager()?to get?android.support.v4.app.FragmentManager.
- getSupportLoaderManager()?to get?android.support.v4.app.LoaderManager
so,?dont?do
or
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.
總結來說就是標紅記錄的說明:
1、fragmentactivity 繼承自activity,用來解決android3.0 之前沒有fragment的api,所以在使用的時候需要導入support包,同時繼承fragmentActivity,這樣在activity中就能嵌入fragment來實現你想要的布局效果。
2、當然3.0之后你就可以直接繼承自Activity,并且在其中嵌入使用fragment了。
3、獲得Manager的方式也不同
3.0以下:getSupportFragmentManager()
3.0以上:getFragmentManager()
轉載于:https://www.cnblogs.com/coolwxb/p/3504948.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Fragment与FragmentActivity的关系的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 回溯法实现n份作业分配给n个人完成的问题
- 下一篇: java--遍历自定义数组