I found a similar question in the StackOverflow forum in English repondida by @MrK that I think is very well explained and she has a lot of positive votes, so I decided to translate it because it fits what you ask.
Translation:
A Fragment
is a section of a Activity
, which has:
- Your own life cycle
- Receive your own input events
- Can be added or removed while
Activity
is running.
A Fragment
should always be embedded in a Activity
.
Fragments
are not part of the API before HoneyComb (3.0). If you want to use Fragments
in an application targeting a platform version before HoneyComb, you must add the Support Package to your project and use FragmentActivity
to save your Fragments
. Class FragmentActivity
has an API to deal with Fragments
, while class Activity
, before HoneyComb, no.
If your project is targeting HoneyComb or newer only, you should use Activity
and not FragmentActivity
to embed your Fragments
.
Some details:
Use android.app.Fragment
with Activity
. Use android.support.v4.app.Fragment
with FragmentActivity
. Do not add the support package Fragment
to Activity
, since it will cause an exception to be thrown.
One thing to be careful with: FragmentManager
and LoaderManager
have separate support versions for FragmentActivity:
If you are using a Fragment
in a Activity
(HoneyComb and above), 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
Therefore, do not do
//don't do this
myFragmentActivity.getLoaderManager();
//instead do this:
myFragmentActivity.getSupportLoaderManager();
or
//don't do this:
android.app.FragmentManager fm = myFragmentActivity.getSupportFragmentManager();
//instead do this:
android.support.v4.app.FragmentManager fm = myFragmentActivity.getSupportFragmentManager()
It is also useful to know that while a fragment has to be embedded in a Activity
it does not have to be part of the layout Activity
. It can be used as an invisible worker for the activity, without its own UI.