Android non-UI Fragment usage

anna picture anna · Jan 24, 2014 · Viewed 13k times · Source

I am going through the Android documentation on Fragments . The layout that defines the UI of a Fragment may be defined in the layout of the Activity, in a separate .xml file or not at all.

According to the documentation

you can also use a fragment to provide a background behavior for the activity without presenting additional UI.

Why would I need to use another Fragment to add functionality to an Activity instead of defining a few more functions within the Activity? Would such a non-UI Fragment be used just for the sake of modularity? Is there another reason for adopting such an approach? I would appreciate an example of when it is suitable to use a non-UI fragment.

Thank you in advance for your assistance.

Answer

marcinj picture marcinj · Jan 24, 2014

I suppose this is about retained fragments, Inside fragment you can call setRetainedInstance(true), this way your fragment will not be recreated during configuration changes. Normally when you rotate your device, all fragments will be recreated. If you call setRetainedInstance(true) inside onCreate(), then your fragment instance will not be recreated.

Whats use of it? - you can put some data, arrays etc. inside your fragment and it will not be destroyed during configuration changes. You can also put async task inside such fragment, and after main activity rotates, your async task in your fragment will still be able to deliver its results.

Another usefull feature of fragments is that you can easily reuse them in multiple activities. This means you can put some common logic inside your non UI fragment. You could lets say accomplish it with base class for your activity, but you can extend only one class.

and simple example from google (actually using Thread inside retained fragment):

https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/app/FragmentRetainInstance.java