Reputation: 4617
Fragment transaction has method add(Fragment fragment, String tag), which does not place fragment to container, so it cannot have view. For what it can be used?
Upvotes: 17
Views: 2686
Reputation: 3091
You can use fragments without UI (container) as a background worker (one benefit is that you can retain it during rotations etc) and for retaining data during rotations and other changes.
Reading http://developer.android.com/guide/components/fragments.html is strongly recommended.
Example of instance retaining: https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/app/FragmentRetainInstance.java
Also, here are similar questions (so this questions seems to be a duplicated but cannot be flagged due to bounty):
Upvotes: 3
Reputation: 2253
By calling the method add(Fragment fragment, String tag)
internally calls add(int containerId, Fragment fragment, String tag)
with a 0 containerId.That will be add(0, fragment, tag).
If 0 is supplied as containerId
, it will not be placed the fragment in a container.
Upvotes: 0
Reputation: 730
As @Lucius Hipan mentions, it can be used to prevent data loss. Almost always this king of fragments are used as Retained container ( setRetainInstance(true) called in onCreate method), then after device configuration changes (e.g. orientation changing) fragment will not be recreated but remembers previous state. It's recommended way to use asynctask.
Here is an example:
There is login activity. The user enters their credentials and presses the Login button. After that configuration change occurs (user rotates phone). So, network task was completed, but your handlers was not listening for it now. If you show any login animation, it can be stored via savedInstance, but listeners not. And instead of creating service you can simply create new retained fragment with persistant asynctask and interface to communicate with activity.
This method is a good compromise for small projects where using bus libraries is overstatement.
Upvotes: 2
Reputation: 3804
From the Android Documentation:
However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.
How about this purpose ?
Simple example: an Activity
starts an AsyncTask
, but when device rotated activity
restarts, causing AsyncTask
to lose connection with the UI Thread. But this Activity
can hold a Fragment
(invisible, with no UI at all) that can handle all the AsyncTask
work. When Activity
recreated the Android OS takes care reattaching the Fragment
, thus no data loss will occur.
Upvotes: 16
Reputation: 2428
For Dialogs you don't have any container on normal app layer. It is directly added on Window with WindowManager(See WindowManager.LayoutParams for various types of layers).
DialogFragment has an API like DialogFragment.html#show(android.app.FragmentManager, java.lang.String) which corresponds to this.
Upvotes: 6