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?
You can simply do it by accessing the view's provided by AppCompatActivity or Activity. Now, you can create a fragment, without adding a view container in your activity you can create as, Show activity on this post. You need to have a layout in your activity to contain the fragment (preferably a FrameLayout).
You create fragments by extending Fragment class and You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element. Prior to fragment introduction, we had a limitation because we can show only a single activity on the screen at one given point in time.
Create a new Fragment without checking savedStateInstance In the Activity (or Fragment), if we have a Fragment as a view by default, then we can create it during onCreate as below. override fun onCreate (savedInstanceState: Bundle?) { There will be a problem with the above code.
Instead, a FragmentTransaction is used to instantiate a fragment and add it to the activity's layout. While your activity is running, you can make fragment transactions such as adding, removing, or replacing a fragment. In your FragmentActivity, you can get an instance of the FragmentManager, which can be used to create a FragmentTransaction.
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.
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.
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):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With