My question is apart from the obvious inheritance differences, what are the main differences between Fragment and FragmentActivity? To what scenarios are each class best suited? I’m trying to get an understanding of why both of these classes exist…
My question is apart from the obvious inheritance differences, what are the main differences
Share
A
Fragmentis a section of anActivity, which has:Activityis running.A
Fragmentmust always be embedded in anActivity.Fragmentsare not part of the API prior to HoneyComb (3.0). If you want to useFragmentsin an app targeting a platform version prior to HoneyComb, you need to add the Support Package to your project and use theFragmentActivityto hold yourFragments. TheFragmentActivityclass has an API for dealing withFragments, whereas theActivityclass, prior to HoneyComb, doesn’t.If your project is targeting HoneyComb or newer only, you should use
Activityand notFragmentActivityto hold yourFragments.Some details:
Use
android.app.FragmentwithActivity. Useandroid.support.v4.app.FragmentwithFragmentActivity. Don’t add the support packageFragmentto anActivityas it will cause an Exception to be thrown.A thing to be careful with:
FragmentManagerandLoaderManagerhave separate support versions for FragmentActivity:If you are using a
Fragmentin anActivity(HoneyComb and up), callgetFragmentManager()to getandroid.app.FragmentManagergetLoaderManager()to getandroid.app.LoaderManagerif you are using a
Fragmentin aFragmentActivity(pre-HoneyComb), call:getSupportFragmentManager()to getandroid.support.v4.app.FragmentManager.getSupportLoaderManager()to getandroid.support.v4.app.LoaderManagerso, don’t do
or
Also useful to know is that while a fragment has to be embedded in an
Activityit doesn’t have to be part of theActivitylayout. It can be used as an invisible worker for the activity, with no UI of its own.