How To Manage The Fragments In Android Correctly?
Solution 1:
Your examples are all valid approaches (basically using the Android transactions to replace fragments). You are encapsulating the common actions into methods, which is always good OO.
Google shows a similar article here called 'building flexible ui's: http://developer.android.com/training/basics/fragments/fragment-ui.html
As for general patterns when using fragments, I try to think of a fragment as a 'section of a screens ui' that may be reused and or can be logically grouped.
When deciding how you organise your fragments when associating activities, there are two that I know of (I have attended many presentations at Droidcon and these are always described):
- Create a FragmentActivity for each logical screen in the UI, then make it manage the one or more fragments that are using on that screen.
- Create one single activity for the entire app which then manages every fragment.
Both are valid, but I usually go with option 1, creating a activity per UI screen and then having that activity manage the fragments used on that screen. It grows better and seems more OO to me.
I only rarely use option 2 if the app is very very compact and small (not many ui screens). As it gets messy fast.
Then as more UI screens are created, I create another activity for it, finally adding that screens fragments.
Although you didn't specifically ask about communication between fragments, I also find that my code is a lot easier to maintain by using one of the Android Event Bus libraries (Green robot event bus is my favourite ,but I hear good things about 'otto' too).
By using an event bus, you can easily communicate between fragments/screens by firing an event.
Post a Comment for "How To Manage The Fragments In Android Correctly?"