Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
First question on Stack Overflow, apologies if it is not well formed.
I am developing a relatively complex tabbed app, and already had the basics set up before coming across information that ActivityGroup and TabActivity are deprecated, and the preferred model is to use views.
I have had no trouble using views, this is a question about architecture rather than syntax (which is why I haven't posted any code). Specifically, how should I go about restructuring the app to use views instead of Intent launched Activities.
The app has five tabs; two hold a single layout, no problem there. The other three tabs are running an ActivityGroup with 2-5 different Activities (i.e. a tab running an activity for settings, where clicking each view starts a new Activity dealing that particular setting, pressing the back button returns you to the broader settings activity/view). If I were to keep each Tab as a TabActivity, it would still be fairly easy to change those internal transitions to views as opposed to separate Activities.
The main question is using ONLY views, no TabActivity/Activity group at all. The vast majority of the research I've done has been discussion about whether to use Activities or Views, or about specific syntax. I haven't been able to gather a clear idea of how to actually MAKE the transition to views across the whole application.
If I were to do so, wouldn't the entire app now be running in a single Activity - the one hosting the tabbed layout?
If (1) is true, how to manage this? Despite ActivityGroup being deprecated, all of the Android documentation still seems to state that it is preferred to use separate Activities for separate aspects of functionality--which makes sense. Did the Android development team simply decide that the costs to the stack and the device made the TabActivity implementation ineffective?
If the application is running in a single Activity that manages different views for each tab (and then different views WITHIN a tab when necessary), should I have one single enormous onClick method to handle all clicks from any clickable view, handling input based on which view is active? Or should I register and de-register all of my Listeners programatically?
With a single Activity, won't any click listener or any broadcast receiver be running all of the time, consuming resources even when unnecessary?
With a single Activity, the back button would exit the entire app from any point in its functionality. If I am using views, won't I have to consistently override onBackPressed() and carefully manage the app behavior to force it to behave "like an Android app?"
AM I THINKING ABOUT THIS COMPLETELY WRONG? It's possible that I am unintentionally attempting to recreate ActivityGroup and TabActivity functionality using views instead, when I should be taking an entirely different design approach to using tabs and Views.
When the people at Google say we shouldn't use activities as tabs anymore, and Mr. Mark Murphy so emphatically agrees, I'm inclined to believe. I simply haven't been able to research-up a way to switch without resorting to recreating a lot of Activity functionality by hand (which would probably include a variety of dirty hacks).
Appreciation in advance for anyone willing to tackle such a vague and overwritten topic.
Using Fragments is the new standard for performing tabbed style ui components, I think you must have just overlooked them because they are the missing piece to all your above questions. Good luck.
Don't forget that using the compatibility library brings Fragment support all the way back to 1.6.
And here is an easy Google recommended tutorial on using Fragments within a TabHost.
About 3) Split your app in as many Activities as you have different parts of the app. Today I'd even go for Fragements that can be easier composed to different layouts when you e.g. make the app for Phone and Tablet.
Most of the time, you can just set up the onClick listeners in the respective xml layout definition files like this:
<ImageButton
android:id="#+id/new_tweet_back_button"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="left"
android:onClick="done"
android:src="#drawable/back_button"
android:layout_below="#id/CharCount"
/>
Here the android:onClick attribute points to a method that implements the handler.
You don't need to de-register anything.
And instead of Tabs I'd go for the ViewPager which makes imo a much more natural experience with just swapping views by swiping left and right (see e.g. G+ app or market app)
As a final answer to my own question:
Using fragments in tabs DID solve all of the above issue.
So, instead of an Activity defining tabs containing other Activities, I have one large FragmentActivity that sets up and switches the views of the various fragments. The click methods defined in the XML for each tab view belong to the FragmentActivity, and I opted to have each onClick call a corresponding method in the appropriate fragment (passing a context if necessary) so the code for manipulating each view programatically can stay in the appropriate class.
THIS IS FOR A PHONE USING THE COMPATIBILITY PACKAGE, not a tablet or Honeycomb, so I can't speak for those unfortunately.
This solution seems to have worked well for me. I recommend anyone looking at the same issue to check out:
thepsuedocoder blog post:
http://thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/
Android documentation on Fragments:
http://developer.android.com/guide/topics/fundamentals/fragments.html
The API demo "Fragment Tabs"
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/index.html#Fragment
Related
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.
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:
master/detail and similar structures for making better use of larger screen sizes while remaining adaptable to smaller screens
pages in a ViewPager
DialogFragment for dealing with configuration changes and dialogs
etc.
Your 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.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Why would someone creates activities as opposed to one activity with many fragments? I see that with fragments, it is easier to share data and plus you have better use of onpause to determine if the app went to background or fragment is being switched.
Am I missing something?
Thanks
(apologies for the long answer in advance)
I don't think anything is stopping you from doing that.
Having said that, How I look at activities is as a place where I can define how the entire UI screen for the current transition should look: which fragments it should include and how these fragments should sit side-by-side and more importantly how the application flow works.
Fragments within my activity should together make a meaningful screen with functionalities I expect and should be re-usable but they shouldn't know of other fragments presence. That's the job of the activity. In fact, I strongly abide by the rule that a fragment should never know of another fragment's existence (although nowadays you can include fragments inside fragments which kind of defeats this point). If I need to transition to a completely different set of use-cases, I prefer to use activities to handle the transition and the new layout and sets of fragments to use.
Do I have to do it? No. I can do it all in one main activity and do the transitions between these "quasi-activity fragments" myself but why would I want to do that when there's already a framework in place that does it for me? Using intents to initialize activities (to transition) is a lot simpler and cleaner to achieve than manually writing my own engine that keeps track of the state of all my fragments and decides which ones to initiate and which ones to get rid of.
Similarly, handling different orientations and device sizes is easier to do using built-in functionalities in activities than doing it yourself but again, nothing is stopping you from doing so.
Much easier to explain this in an example:
Imaging this use-case: I need to write an app that shows a list of songs and movies. When I click on one of the songs, it should open a media player and play it in a separate screen and when I click on a movie, it should open a video player and play the video. There are clear transitions here: From the main list to an audio player or a video player and back.
Doing this using only one activity and 3 fragments, I would have to replace the list fragment with an appropriate media player fragment (video/audio) and get rid of the list fragment myself (to preserve memory) when the user clicks on a list item. This is all fine and easy to do but what happens if I have to also add a way to add comments to songs/movies? Now I have to modify my main (and only) activity to understand the behavior that if someone is playing a song and clicks on the comment button, I need to transition again to yet another fragment and allow that fragment to capture/show comments.
As you can probably imagine, every time I add a new functionality, I have to modify my main activity to handle the transition since fragments are not meant to know about each other and are meant to be independent of each other.
What I would end up doing, if I only had one activity, would be to create a God class (my main activity) where the entire flow of my application is defined. Maintaining this flow will become more and more complicated as the app becomes complicated. Again, this is going on the principle of having independent fragments. If you don't care about your fragments knowing about each other, that's entirely different but then, in my opinion, you're doing it wrong :)
How would I do it using activities? I would still have 3 fragments but also would have 3 activities whose only job is to maintain the transitions to/from other activities and defining which fragment should be used. Transitioning between list activity to song activity is a simple intent and the freeing up memory is done for me. Now if the song activity needs to transition to a comment activity, it's simply another intent to a comment activity from the song activity. I don't have to change the list activity at all and in fact, the list activity will never know about the existence of this comment activity.
I know it's a very simplified example but as your app gets more and more complex and as you add more and more use-cases, you'll find that having multiple activities makes sense. You don't want to maintain the transitions between fragments yourself, otherwise you'll end up with a very complex framework which would slowly become unmaintainable.
Same logic would apply to having different fragments/layout depending on the orientation and the size of your screen. Again, by all means, you can handle these yourself in your only activity but the question becomes: why?
I think your question can be answered by two other questions:
What can Fragments do that Activities can't?
You can reuse fragments in layouts for phones and tablets, where the content that is presented in multiple screens on the phone appears as multiple columns in tablets.
Fragments can better retain instance state across configuration changes, with setRetainInstanceState(true).
You can nest Fragments inside other Fragments, each of which can have a different layout.
You can create Fragments without a user interface, unlike Activities, which should always have a content view.
What can Activities do that Fragment's can't?
Launcher Fragments don't exist, only launcher Activities.
Activities can be started from other apps with Intents.
Activities can be started as new tasks.
You can use Activities in older versions of Android, which is no longer that big of a deal since the usage rates of these older versions of android are pretty low nowadays.
While this list is certainly not comprehensive, there are many cases in which you could use either an Activity or a Fragment for the same content. Pick whichever one helps you keep your code organized. Fragments are good for reusable components where Activities are good for standalone capabilities. Personally, I tend to prefer using Activities unless there is a reason to use Fragments. I find that managing too many Fragments within a single Activity is tedious and error prone.
As I've started to adopt Fragments more and better but also as Fragments functionality is increased (Fragments in Fragments, MapFragments) I'm starting to reach a point where I need to define when I should make a new View/Action as a Fragment or as an Activity?
An Activity is defined as:
An activity is a single, focused thing that the user can do.
But a Fragments have kinda taken that definition instead as described in the docs:
For example, a news application can use one fragment to show a list of
articles on the left and another fragment to display an article on the
right—both fragments appear in one activity
This is two things the user can do in one Activity with two Fragments.
So I'd like some input/help to figure out what is the best approach to decide if I should make a new action/view as a Fragment or as an Activity?
The answer depends on you and your development practices (or those of your company). However, my opinion is this: At a minimum, if you think the functionality being developed could be used within multiple Activities, or if it could ever be used in an Activity alongside another view (as on a tablet), then you should make it a Fragment.
We've recently adopted the philosophy of creating Fragments in all cases. Our Activities are now just top level coordinators, basically the glue that brings things together. This makes for a consistent and flexible architecture. This is important to us as we have numerous engineers at a couple of locations working on code.
An Activity is defined as: "An activity is a single, focused thing that the user can do"
That is more an issue of dated documentation than anything else. Activity has that same definition... when we are on a smaller screen size (e.g., phone). As you move up to larger screens, the odds of an activity being more complex than "a single, focused thing" increases.
So I'd like some input/help to figure out what is the best approach to decide if I should make a new action/view as a Fragment or as an Activity?
Here is my general heuristic:
If you anticipate that such-and-so piece of UI might exist standalone on a phone-sized screen, but be used in tandem with something else on a tablet-sized screen, make it a fragment.
If you anticipate that such-and-so piece of UI will always exist standalone, just create a simple activity.
If you anticipate that your ability to anticipate is not that good, err on the side of making more fragments. For example, you might say, "well, help will never need to be alongside anything else" and make it be an activity. Then, if you realize that other pieces of UI might benefit from the help being side-by-side with them rather than off on its own -- so the user can read the docs and perform the actions at the same time -- you will regret not having made help be a fragment, as you will have to do some re-work.
If such-and-so piece of UI would never exist standalone -- in other words, if it is more like a single widget than a full activity -- and you anticipate using it on multiple projects, make it be a single widget, in the form of a custom View or ViewGroup.
But, as jsmith indicates, there is no universal right or wrong answer. BTW, AFAIAC, jsmith's answer is the correct one here, but I was going to be way too wordy for a comment on his answer... :-)
I've been developing in Android since 1.5 so I have been developing from quite some time Activities and recently Fragments.
Quite frequently fragments left me with a sour taste in my mouth... an example was when I needed a kind of paginated Dashboard with buttons. For that I used a ViewPager + 1 fragment per button. I had all kind of problems because before Android 4.2 fragments couldn't be nested.
Another problem was the asynchronous mode of function of the fragments that when the needed to be moved from one place to the other quite rapidly it had all kind of misbehaviours.
Don't think that all was bad... in more simple cases, the use of fragments worked quite nicely.
So, in my opinion, whenever you have an area that is self-contained, that isn't moved frequently on the views, that can be reused in several screens and also you support tablets (or my in the future), use it.
If you need nested fragments, views that are re-arranged quite frequently, or code that will not be reused, don't.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am thinking of implementing one screen with Activity and all other sreens with Fragments and managing all the fragments thru the activity.
Is it a good idea? and my answer is NO but still I want to know more clearly about this thought.
What are the pros and cons of the idea?
Note:
Please don't give me the link for fragment and activity.
EDIT:
Here is something over Fragments and activity:
Pros:
Fragments are meant to be used with activities as a sub activity.
Fragments are not the replacement for activities.
Fragments are meant for reusability(Need to know in what way reusability can be achieved.).
Fragments are the best way to write code to support both tablets and phones.
Cons:
We need to implement the interface to get the data from fragments.
For dialog we have to go a long way to show it.
Why should we use fragments if we are not considering tablets?
What is the starting time difference between activity and fragment?
It depends on the app you are creating. I've created several apps using both approaches and can't say one way is always better than the other. The latest app I created I used the single Activity approach and a Facebook style navigation. When selecting items from the navigation list I update a single Fragment container to display that section.
That said, having a single Activity also introduces a lot of complexities. Let's say you have an edit form, and for some of the items the user needs to select, or create, requires them to go to a new screen. With activities we'd just call the new screen with startActivityForResult but with Fragments there is no such thing so you end up storing the value on the Activity and having the main edit fragment check the Activity to see if data has been selected and should be displayed to the user.
What Aravind says about being stuck to a single Activity type is also true but not really that limiting. Your activity would be a FragmentActivity and as long as you don't need a MapView then there are no real limitations. If you do want to display maps though, it can be done, but you'll need to either modify the Android Compatibility Library to have FragmentActivity extend MapActivity or use the the publicly available android-support-v4-googlemaps.
Ultimately most the devs I know that went the one Activity route have gone back to multiple Activities to simplify their code. UI wise, on a tablet, you are some times stuck using a single Activity just to achieve what ever crazy interaction your designers come up with :)
-- EDIT --
Google has finally released MapFragment to the compatibility library so you no longer have to use the android-support-v4-googlemaps hack. Read about the update here: Google Maps Android API v2
-- EDIT 2 --
I just read this great post about the modern (2017) state of fragments and remembered this old answer. Thought I would share: Fragments: The Solution to All of Android's Problems
I'm about to finish a project(5 months in development), that has 1 activity, and 17 fragments, all full screen. This is my second fragment based project(previous was 4 months).
Pros
The main activity is 700 lines of code, just nicely managing the order of the fragments navigation.
Each fragment is nicely separated into it's own class, and is relatively small (~couple hundred lines of ui stuff).
Management can say, "hey, how about we switch the order of those screens", and I can do it very easily, as those fragments don't depend on each other, they all communicate through the activity. I don't have to dig through individual activities, to find where they call each other.
my app is very graphics heavy, and would never work as 1 screen 1 activity. All those sub activities in the memory, would make the app run out of memory all the time, so I would have to finish() all non visible activities, and make the same control logic for navigation, as I would do with fragments. Might as well do it with fragments just because of this.
if we ever do a tablet app, we will have an easier time re-factoring stuff, because everything is nicely separated already.
Cons
you have to learn, how to use fragments
First, whatever you do, make sure you have a modular design using model, view, presenter that is not highly dependent on an Activity or a Fragment.
What do Activities and Fragments really provide?
Life cycle events and backstack
Context and resources
Therefore, use them for that, ONLY. They have enough responsibility, don't over complicate them. I would argue that even intantiating a TextView in an Activity or Fragment is bad practice. There is a reason methods like public View findViewById (int id) are PUBLIC.
Now the question gets simpler: Do I need multiple, independent life cycle events and backstacks? If you think yeah maybe, use fragments. If you think never ever, don't use fragments.
In the end, you could make your own backstack and life cycles. But, why recreate the wheel?
Pros
You could control your fragments from a single activity, beacause all fragments are independent of each other. The fragments have a lifecycle (onPause, onCreate, onStart...) of their own. By having a lifecycle, fragments can respond independently to events, save their state through onSaveInstanceState, and be brought back (i.e. such as when resuming after an incoming call or when the user clicks the back button).
Cons
Create complexity in your code of activity.
You have to manage the order of the fragments.
Never the less, it is quite a good idea, as if you need to create an app, where you want to show several views. By this idea, you'll be able to view several fragments in a single view..
It depends on the design layout of your app. Suppose if your using Tabs in ActionBar in the design layout then in the Single Activity of the app one can have fragments being changed on Tab click. So now you have an Activity and say suppose three Tabs in the ActionBar and the view for the tabs being provided by the Fragments, which makes it easy to manage plus is feasible also.
So, it all depends on the design scheme of your app and how you take the decision to build for it.
Pros:
Can be used to create a single interface usable by multiple screen sizes and orientations via xml layouts.
Cons:
Requires more complex code in your activity.
I believe it's a good idea, because using different xml layouts based on the current screen size and orientation can make the app more usable and reduce the need to release multiple versions of your app if you plan on releasing your app for both phones and tablets. If your app will never be used by both tablets and phones, it's probably not worth the trouble.
I'm a proponent of deferring all view inflation to fragments to provide better flexibility. For example having a single landing activity for a tablet which aggregates multiple fragments and reusing the same fragments on a phone to show one screen per fragment. However in the phone implementation I'd have a separate activity for each screen. The activities would not have too much code as they would immediately defer to their fragment counterpart for view inflation.
I think it's a bad idea for the phone implementation to have to change to a single landing activity when tabs or a slide out menu is introduced since the tab or menu navigation just results in a completely new screen.
The most important reason I would give for not using the single activity approach is so that the activity lifecycle can be taken advantage of. Activities contain contextual behavior of a certain portion of the application and fragments supplement that behavior. Having the ability to take advantage of the overridable steps in the activity lifecycle helps to separate one activity's behavior from another with methods such as onPause and onResume. This lifecycle also allows you return to previous context. With the single activity approach, once you leave a fragment you have to create an mechanism to return to it.
I'm looking for the the best way to reproduce, in an Android app, the behavior of the iPhone UiNavigationController within an UITabBarController.
I'm working on this Android app where I have a TabActivity and 4 tabs. I've already gone through a lot of posts regarding the use of activities and tabs and how it's not a good idea to use activities for everything, which seems fair enough. I decided to use one Activity on each tab anyway, since it makes sense in my application.
However, in one of those activities I have a deep navigation tree with more than one branch and up to 12 different views the user can go through.
The problem is: Android controls the navigation through activities inside an app, if you click the back button it will go to the previous one, but if I'm navigating through views, using one Activity, and I click back, it just finishes it. So how can I have a smooth navigation behavior between views in an Activity?
I had implemented this using a TabActivity with FragmentActivity as each tab. Utilizing Fragments API you can organize the code just like you would be using 12 different activities, still using only 1 for each tab in fact. Fragment's framework will handle back key press for you to show previous fragment instead of closing the entire activity.
There are some problems with such approach, for example, there's no MapFragment, but the workarounds can be found here on SOF.
You will need Android Support Package if your minimum SDK version is lower than 3.0.
Well I know very little about UiNavigationViewController, but I guess you want something to navigate between different Views. As you are using TabActivity, every tab should load into a separate Activity.
But since you want to branch it out, using that many Activities is not a perfect solution, neither the ActivityGroup too. The better solution, as per my opinion(I have run into similar problem once) is to have the main or root tabs loads into separate Activity, but for their branches, use the ViewFlipper, which flips the Views. So the whole Layout(Subclass of View) can be flipped.
You may run into some problem while flipping more than two Views (as what people say, though I never had any problem). So in that case you can use layout.setVisibility(View.GONE) to hide the layout and just change it with View.VISIBLE for next view.
And about the concerns of back button, you need to store the last used View or Activity into a variable, and in the override of onBackPressed(), just need to call them.
There might be better solution than this, not that I can remember, but yeah it's the easiest solution I can come up with.