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 6 years ago.
Improve this question
I know this question probably gets asked a lot, but I wanted to get an answer specifically for the kind of app I'm building. I'm creating an Android app, which is basically a recipe search app which allows the user to choose ingredients, food categories, and preparation time and the app would find recipes that fit the user's search.
There are individual "pages" for ingredients, categories, and time, and I have created an activity for each. The user picks ingredients first, then when they click Next, the category activity is started, and then once again when they click Next, the preparation time activity comes up. Then when they click Search, I have another activity for results, and when the user clicks one of the recipes in the results, another activity for displaying the recipe starts.
So I have the following activities, where each activity starts the next in the following order:
IngredientActivity
CategoryActivity
TimeActivity
ResultActivity
RecipeActivity
I did some reading and found out that I should have probably used fragments. My plan is to change my app so it would have a tabbed activity with three tabs for ingredients, categories and time, with a Search button at the bottom which is displayed in all three fragments, which allows the user to easily switch between tabs and search from whichever tab they're currently viewing. As for results and displaying recipes, I'm thinking to leave their respective activities as they are. The Search button starts the ResultActivity, and clicking on an individual search result starts the RecipeActivity and displays the recipe the user clicked on.
In addition, I'm planning to add a "search by recipe title" function. The user would be able to switch between those two search modes using a menu button in the action bar. I'm assuming each search mode would have to have a separate activity, so that's what I'm planning to do.
Is my idea the correct way to do it? Or should I have just one activity for the entire app and do the rest exclusively with fragments?
For me, all decisions about Activity or Fragment are related to (1) UX (2) Manageability (3) Communication cost across components, etc.
Let me introduce some decisions by examples.
Is the screen required to launch from outside (Share intent)?
Activity is better as it can be opened directly from what AndroidManifest gives.
Does the screen require page-by-page views (recipe pages)?
Fragment is better as Fragment+ViewPager give flexible paging fuctionality. Moreover, some Android devices or theme editors override Activity opening effects so page-turning animation does not run as expected if we implements it in Activity-by-Activity manner.
Does the screen execute Camera or Photo intent with StartActivity?
Activity is better as OnActivityResult is hard to manage inner fragments when the app restores back from the Camera apps. For this reason, "writing a post" screen could be a good example to be a single Activity.
Does the screen have to run regardless of screen on/off (Timers)?
Activity is better as it can show up faster and lighter without Activity-Fragment dancing.
Does the screen have a kind of master-detail hierarchy?
Fragment is better because we could prepare tablet layout.
Does the screen consume memory a lot?
Activity is better because we can focus on the activity solely not inner fragments memory usage.
Does the screen has nested fragments more than 3-depth?
Fragment, reluctantly. Communication between fragment is unstable and Activity-Fragment bridging/dancing is always headache 1 2. We can make complexity lower but Activity-inside-Fragment-inside-ViewPager-inside-fragment-... is hard to acheive manageability.
Using multiple Fragment with single Activity is recommended by professional Android developers but we could decide to create more Activities for easier management and faster understanding.
In your case, I would like to implement components as below.
MainActivity with Fragments: Ingredients, Categories, Recipe.
ResultActivity with Fragments: Search and its Results are a kind of master-detail view.
TimerActivity: It should be good to run in single Activity.
RecipeActivity: If each recipe has its own id and can be shared as permalink, your app could open directly the recipe page by RecipeActivity. And, it could be better to show recipe even if your app is restored from turned-off or switched back from another app situation.
Related
I developed an app for the iPhone that I would like to make for Android. However, because I was self taught with Xcode, I approached the project incorrectly. My app in it's basics loads a certain picture from a List View when the user selects the certain button associated with the picture they want. I had no programming experience when I started, so I just linked by drag and dropping roughly 300 buttons to 300 different scenes which displayed 300 different pictures in Xcode. Yes, it was very time consuming... My question is how should I approach my project to do the same function in Android Studio, but minimizing the amount of activities. I have the idea that it would be more beneficial to use code to have one List View activity that incorporates many buttons, that when pressed, will display the particular picture. Any recommendations for tutorials or videos as a place to start as I learn my way around Android Studio? Or am is it hopeless and I will have to have another roughly 300 Activities in Android Studio.
You can use fragment for acheving your purpose.
A Fragment is a piece of an activity which enable more modular
activity design. It will not be wrong if we say, a fragment is a kind
of sub-activity
Fragment you can think of it like a sub activity, which sits with in
an activity and which contributes its own UI to the activity screen.
Fragments are always part of an activity. With out an activity, a
fragment will not exist. So your fragment life cycle will always be
affected by activity life cycle. An activity can contain more than one
fragment. Similarly a fragment can be re used in multiple activities
Below links will help you to know more about fragment and how it's implemented in an android application
https://stackoverflow.com/a/13757241/4247543
https://www.raywenderlich.com/117838/introduction-to-android-fragments-tutorial
https://www.tutorialspoint.com/android/android_fragments.htm
https://developer.android.com/guide/components/fragments.html
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.
I need to develop an application which contain these tabs shown in the image. Each tab contain a form which will be filled by the user.User can switch to any tab.
User click Activity1, Activity 1 gets displayed and user enters some data; then user press Activity 2, activity 2 gets displayed, user press Activity1 again, Activity 1 gets displayed with the data entered by the user(not the blank activity).
At the end when user click "Save" I need to get all the data from these activities and save it somewhere.
I have worked a lot in java but new to android, I am stuck in developing the UI for this scenario. However I have done this many times in iOS.
Anybody please share your experience of developing such UI.
Thanks,
Fragments will be more suitable for this scenario, the benefit are
They are light weight and faster
Managed automatically by the FragmentManager.
Data Sharing between Fragments is smoother and simpler than it is for Activities
They don't complicate the Architecture of the Application
You can have as many Fragments as you want in you Activity. Following two links can be useful for you.
A similar Thread
A Good Tutorial
Another good tutorial
If even after that you decide to use Activities, You need to think
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.
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 9 years ago.
Improve this question
I'm starting Android doing an application for searching restaurants, and some guidance would be welcome!
On the first screen I'd like to have a search field with a submit button (I get the data from a web service), and below a list with the results of the search. When clicking on one of the items of the list it will show a screen with the restaurant details as well as a map showing its location. My questions are:
Can I do everything in one single activity or should I do an activity for the search, one for the result list, one for the restaurant description, and another for the map?
Would doing one single activity make the application more responsive?
How can I use a list and a map within a normal activity (without ListActivity and MapActivity)?
Can I do everything in one single activity or should I do an activity for the search, one for the result list, one for the restaurant description, and another for the map?
The answer to this really depends on the flow of your application. I think the most important thing to keep in mind here is how the user will control your app with the "back" button. When you create a new Activity, that puts it on the stack, and the user can always press "back" to pop it from the stack.
One extreme is to put all these steps into different Activities. Then the user has ultimate control using the "back" button, but they might get annoyed jumping around Activities. Putting it all into one Activity is the other extreme, and I highly advise against that; users expect new screens to be a different Activity, one that they can "back" out of, and so if you put all your eggs into one Activity you'll have to start handling "back" yourself.
I think there's a good middle ground that your app could take, though of course your UI design may differ than what I propose. I would say you could do this in two Activities; in the first, you have a search field at the top (with a submit button next to it), and below that search field is a ListView which is populated with results. In the second, you use a TabActivity, where one tab is for the description and the other is for the map. I think this is advantageous for two reasons: on the first Activity, the user sees the results of their search on the same page as the search, and can quickly change the search parameters if necessary. And on the second Activity, the back key encapsulates backing out of one restaurant.
Would doing one single activity make the application more responsive?
Not really. Activities take time to create/tear down, but not that much time. It's better to segment your application in a logical way (for the user experience).
How can I use a list and a map within a normal activity (without ListActivity and MapActivity)?
You can get away with a ListView inside of a normal Activity without ListActivity; just include a ListView in your Activity's content, then in code grab the ListView and set its adapter manually. All ListActivity does is add some handy wrapper functions for one primary ListView, but it's not necessary at all.
Maps are a different matter. You will need to use a MapActivity for displaying maps, because MapActivity has special setup and teardown code that needs to run. Sorry.
I would like to add some guidance to Daniel's excellent answer.
Users can't tell the difference between one activity with views that change and multiple activities each with their own view - until they press the back button. So it is actually quite important that the back button should have a natural and logical purpose in relation to what is on the screen when it is pressed. The user should never be surprised by what happens when they use it.
So for each activity you have, ask yourself if the behaviour of the back button is logical to the end-user at all times. If you find a scenario where it is not then you should look at refactoring your activities - which could involve combining two or more activities into one, moving some responsibilities from one activity to another (but keeping them both), or even splitting an activity in two.
Creating a user interface that behaves logically as the user navigates around it is important, and the more your application does (and the more navigation there is) the more important it becomes. Unpredictable navigation behaviour stops people from learning how to get the best out of your application at the time when they are most likely to uninstall it - in the first few hours after downloading it.
I would have an Activity with both the search and list, then another that shows the details of the restuarant.
I don't think it would work well with just a single Activity.
Activities can contain multiple views - a single activity can contain a map and a list if necessary.
If you are looking to write modular, reusable and portable code, one activity is the way to go. Activity is an Android-only concept. The main flow and the business logic of any well-designed application should be platform-independent. Involving activities in your higher-level code ties your project to Android, which goes against platform-independence, a core principle in both Java and quality programming in general.