Reputation: 1359
I'm a beginner in Android programming, and have trouble understanding the activity - fragment principe. As far as I understood, fragments are something like "sub-activities", and I can add multiple fragments in one activity, but also I can have an Activity without any Fragments. Answers to the question "why use fragments at all" can be found all over the net, also there are some stack overflow questions to this topic. But my question is: If there are advantages in using fragments - why to use activities then? If fragments are "better" and I should use them everywhere I can, then all my Activity classes will be empty, and the fragments will bring the content to the screen - is this the best practise?
If i want to add a menu for example - I can put it only in the fragment, so what's the point in adding setHasOptionsMenu() in the Activity class?
To be more specific: What should I put in activities, and what in fragments?
I hope you understand my problem.
Upvotes: 0
Views: 60
Reputation: 1006779
But my question is: If there are advantages in using fragments - why to use activities then?
Because you don't have a choice. Activities are part of the Android foundation. You cannot have a launcher icon invoke a fragment directly, for example.
so what's the point in adding setHasOptionsMenu() in the Activity class?
In many UIs, there will be action bar items that have nothing to do with any particular fragment: "Settings", "Help", "About", and so on. Those are perfectly fine to define in the activity.
What should I put in activities, and what in fragments?
At the end of the day, you are welcome to do whatever you want, so long as it compiles, runs, and does what you want reliably. You can roughly divide the approaches into three "schools of thought" around fragments.
The simple one is, "fragments are teh evilz and must be destroyed". Adherents will use something else (e.g., Square's Flow and Mortar) as an alternative.
The more complex one is "use fragments where they prove useful". The definition of "useful", like beauty, lies in the eye of the beholder. So, you will see people use fragments for:
ViewPager
DialogFragment
for dealing with configuration changes and dialogsYour current position is the third school of thought: "Fragments Über Alles". The difference between this and the "where its useful" scenario is that you would apply fragments even in cases where there is no clearly defined use for them. For example, a HelpActivity
, whose sole UI consists of a really big WebView
showing your documentation, would not necessarily benefit from having that WebView
be managed some subclass of WebViewFragment
. The "where its useful" people would skip the fragment until some clear need arose (e.g., you want the help to be side-by-side with other content in an activity on larger screens) The "Fragments Über Alles" adherents would use the WebViewFragment
all the time.
Upvotes: 4