Android non-UI Fragment usage [duplicate]

僤鯓⒐⒋嵵緔 提交于 2019-11-27 02:35:47

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/21335796/android-non-ui-fragment-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!