I am new to developing on android, finding myself somewhat confused regarding fragments and activities, and when to use the former specifically.
I want to achieve the following:
Have an activity with buttons for displaying different graphs. The selected graph should appear on screen in a panel overlaying the screen, or in fullscreen, and it should have functionality/buttons e.g. for selecting a graph timeframe.
Would creating each graph-page as fragments, routing events to the main activity be a good idea here, or should I just make a new activity for each? Or are there better options?
Cheers
I wouldn't recommend to use separate activities for this task.
The fragments are a great option for your case. You can save the state of each fragment and thus avoid recreating the graph views every time (which saves lots of CPU time if amount of data is big).
Read info about FragmentTransaciton and of course learn about working with Fragments in general. Maybe you should also try using ViewPager if you want to avoid switching fragments by yourself.
In case of using ViewPager you should use FragmentPagerAdapter (this one saves fragments for you) and you will just switch between them from your MainActivity. In each of the fragments you will implement your own graph with its own (or shared) layout file.
This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible.
Related
I have a NavigationView used as a slide-in menu. Each of that menu items is a use case itself, therefore I tend to using activities containing different fragments.
But nearly every example of NavigationView/NavigationDrawer uses fragments, so I don't know what to use here.
I thought different use cases should be "encapsulated" in own activities, therefore I don't really understand why Navigation[View/Drawer] uses fragments. And that leads me to my question: for a Navigation[View/Drawer] containing completely separate use cases - should I link to activities or fragments?
I posted a similar question
I have created around 4-5 apps with mid-big size project. I used Fragments for Navigation Menu clicks and had to manage lots of Lifecycle events and Memory Leaks and shit stuff. The Performance degrades and app becomes slow.
Then in one of the app I Used Activities for each Navigation menu clicks, treating it separate Entity/Module. This Activity would then use fragments if they had child views.
Doing so I had a great app, less trouble and I could concentrate on Business Logic rather than maintaining fragments.
Although Google recommends Fragments, But I never liked them, they always put me in trouble and handling them is a mess.
In my current Project I have created a BaseActivity implementing Navigation and all the other Activity extend it.
the NavigationDrawer and the contents are all just Views inside the Activity view hierarchy.
The use it of fragments is usually shown in tutorials because you can encapsulate each item inside a fragment, and fragments is the usual Google advice, even though they're a pain in the ass and have horrible drawbacks regarding animation.
But the direct answer to your question is: It's all just a matter of structure and organisation and it really does not matter how you do it, because in the end they're all just views in the Activity view hierarchy.
You can "manually" inflate views and put in the content area.
You use fragments to separate the views and logic and their own container.
You can use activities with different content and the same NavigationDrawer.
sorry for asking this question again. I have read all related articles, but haven't figured out what is better to use and when.
My app is going to be online store native client.
So I have a bunch of different screens in my app.
First Screen. It will be main screen like in the most online stores. There will be image slider, last new products, sales, ad and other common stuff for store.
Second screen. There will be simple list of categories in the store, without any ad,sliders and so on. Only list (RecyclerView).
Third screen. Will represent description of product, price, photos and other.
Fourth screen. Login and sign up screen to let user login in it's account.
There would be a lot of other screens required for native store client.
I have some questions about this.
I have watched the video, where lecturer said that in their app they are using only one activity for all app except settings and payment. So it makes app smoother, responsive because fragments are more lightweight that fragments. Okey, in this case we have base Activity, it should implement all callbacks from fragments to handle data and replace screen with another fragment.
We can use event bus to make it easier to with callbacks, but there is another problem.
How my activity layout should be built, it should have one fragment container and we can replace whole screen with another fragment or activity should include several fragments. For example for each image slider, ad, last products use its own fragment?
If we will use one container, so in this case we change whole screen. Is there any benefit of using fragment in this case ?
If use several fragment per screen. We have to put them in parent framgent ? In this case we are dealing with nested fragments. In most cases it is bad practice to do so.
Or we have just to know about all fragments currently present on the screen and when we have to change all screen view remove all old fragments and add new ?
What about nested fragments? Is bad to use them, and I have to do my best to get rid of them ?
Please explain how to build app to make it responsive but also to make code pattern and best practices oriented.
Thanks everyone for the help in advance.
I tried both ways, each for long period of time! I think both ways of developing applications are completely okey! I prefer fragments mostly because app looks and feels smoother but working with fragments may add a little bit of complexity to your application especially in your first project.
Should you have only one container in activity? Yes! because it doesn't matter how complex your app is, you always have some simple pages like about us, contact us, etc. and most likely they need to be full screen size! So your main activity should only have one container.
Is using nested fragment a bad idea? No! there is nothing wrong with nested fragments, in fact using nested fragments correctly will reduce the complexity of your app, that's because your main activity doesn't have to worry about little details in fragments, there transitions, navigation, etc.
Is using multiple fragment in one screen okey? again yes! that's the beauty of fragments, you arrange them as you like. Only ask one question before using multiple fragment in a screen. Do i need fragments or i just need to combine some views together?! In second case you don't need fragment, You can build a custom view that's combine some views together. (for example two textviews and one button for logging screen). Now instead of login fragment you have logginView than you can use like any other view.
Last thing you should know is using one activity increases the chance you get memory leaks (in particular activity leak) and when you get a memory leak it will be harder to find and handle it. why? because every fragment has a reference to activity (remember method getActivity?) so if you leak any fragment you also leak the activity and since your activity contains a lot of things you leak all of them all together!! And also all views have a reference to context. So again if you leak one view by accident, you leaked everything!! So be very careful about memory leaks. here is a detailed artical about memory leaks here http://goo.gl/7YDCK7
We recently converted an app from a multiple activity based one, to one with a single activity with multiple fragments. The activities that became Fragments used to contain fragments themselves, so we use child fragment managers to host the Fragments in the Fragments (these child fragments I should add, are small and there can be 4 or 5 these on the screen at one time).
This has caused a few issues, namely having to create, and keep track of Unique IDs for the Fragment holders. (Which cause headaches when dealing with the Backstack as well as if any are in any sort of AdapterViews).
We're thinking of just rewriting these components to extend some sort of ViewGroup, likely FrameLayout or LinearLayout. We already do that anyway in some cases, but I was wondering if there are any disadvantages to doing it that way? (I must admit, I don't really see the big deal about Fragments... anything you can do with Fragments, you can do by creating a Custom View. Is this wrong?).
This is a bit of a reverse answer, explaining fragment use. In general you can do most things with Activities, but as the SDK supports fragments, many things will become more cumbersome (ViewPager is an example where fragment use is great).
The advantages (of fragments): code encapsulation, reusable chunks of UI.
The disadvantages (of fragments): more code (e.g. FragmentManager, FragmentTransaction).
Your original use of activities was good, it's not a case where I would have switched to fragments.
Let's say I designed a mobile phone app with two activities: ContactList and ContactDetails. So far so good, no reason to use fragments yet. If I wanted to support a larger device, it would behoove me to display both screens side by side. This is where fragments come in handy. In terms of exactly how to structure your activities/fragments, there's some good advice here:
https://developer.android.com/guide/practices/tablets-and-handsets.html#Fragments
Here are the important bits:
Multiple fragments, one activity:
Use one activity regardless of the
device size, but decide at runtime whether to combine fragments in the
layout (to create a multiple-pane design) or swap fragments (to create
a single-pane design).
Or...
Multiple fragments, multiple activities:
On a tablet, place multiple fragments in one activity; on a handset,
use separate activities to host each fragment. For example, when the
tablet design uses two fragments in an activity, use the same activity
for handsets, but supply an alternative layout that includes just the
first fragment. When running on a handset and you need to switch
fragments (such as when the user selects an item), start another
activity that hosts the second fragment.
.
The approach you choose
depends on your design and personal preferences. The first option (one
activity; swapping fragments) requires that you determine the screen
size at runtime and dynamically add each fragment as
appropriate—rather than declare the fragments in your activity's XML
layout—because you cannot remove a fragment from an activity if it's
been declared in the XML layout. When using the first technique, you
might also need to update the action bar each time the fragments
change, depending on what actions or navigation modes are available
for each fragment. In some cases, these factors might not affect your
design, so using one activity and swapping fragments might work well
(especially if your tablet design requires that you add fragments
dynamically anyway). Other times, however, dynamically swapping
fragments for your handset design can make your code more complicated,
because you must manage all the fragment combinations in the
activity's code (rather than use alternative layout resources to
define fragment combinations) and manage the back stack of fragments
yourself (rather than allow the normal activity stack to handle
back-navigation).
I have a question about whether to use View or Fragment with ViewPager.
Background:
I have an Activity A that contains a ListView. Each ListView item opens Activity B. Activity B shows different content depending on which ListView item is tapped in Activity A.
Activity B's content is shown inside a ListView.
Question:
Now, instead of going back and forth between Activity A and B to switch contents, I have a requirement to implement horizontal view swiping to switch contents all within Activity B.
One solution I found (tried it and it works) is to create many instances of Activity B's ListView and use it with ViewPager + PagerAdapter.
Another potential solution found on the doc (haven't tried it) is to bring that ListView into a Fragment, create many instances of the fragment and use it with ViewPager + FragmentPagerAdapter or FragmentStatePagerAdapter.
My question is, what's the benefit of using each approach? Should I go through all the trouble of bringing the ListView into Fragment or just simply use ListView with ViewPager?
Thanks
A Fragment is a useful approach, I think, when you want to tie some UI business logic to a particular View (or group of). As you know, that individual Fragment has its own lifecycle callbacks and so forth, just as an Activity would.
Rather than having a single Activity host many ListViews through a single PagerAdapter, it may be cleaner to use the Fragment approach because the Fragment only needs to deal with the logic behind driving a single ListView.
This is a very similar situation to one I've just been facing. I'm showing various vertically scrolling forms (consisting of lots of input fields) within a ViewPager. In my case I have gone for the Fragment approach because in my case, it's possible that the ViewPager will actually need to display a completely different kind of view on certain pages. For example, on the first few pages, user input forms might be displayed. But on the final page, a graph will be displayed. A whole separate set of logic is required to drive that graph. To drive those input forms and one graph from a single Activity would get a bit messy, and I would probably need to contain the business logic in several delegate classes or something. So for me, Fragments were the obvious choice in the end. I have my InputFormFragment and a GraphFragment, and they each contain only the applicable logic for the Views that they supply.
Another thing to consider is that in the near future you too may want to display a different kind of View in your ViewPager. Or, you might want to have another UI layout altogether, perhaps one that doesn't use the ViewPager but displays them all side-to-side (e.g. a layout used on a large tablet in landscape mode). With Fragments, things are just far more modular and you could factor the code to do this quicker. If on the other hand you achieved your objective by using a single Activity that contains a simple PagerAdapter and all the logic for the ListViews within, you might find it takes more work in the future to support new kinds of Views or special tablet layouts.
One thing I will say is having implemented Fragments in a ViewPager myself through FragmentPagerAdapter and FragmentStatePagerAdapter, things can get a bit awkward if you have any special requirements; managing Fragments can be tricky sometimes. For example, for my UI I needed to be able to programmatically add and remove the ViewPager containing the Fragments. I also needed to ensure that the adapter in use didn't destroy Fragments once they had been shown, because I needed to collect data from all Fragments simultaneously at a certain point. Furthermore, I had to extend and modify FragmentPagerAdatper to make sure that the Fragments go through their onDestroy() properly and are removed from the FragmentManager when the ViewPager was removed.
Fragments enable a very modular way of constructing UIs for various screen sizes and orientations, and are excellent in how they allow you to encapsulate business logic and lifecycles for individual UI elements. However if your scenario really is just as simple as several ListViews in a ViewPager and you know that you will never need the modularity, then the overhead of Fragments could be an overkill.
I'm writing an app for phones and tablets. Like the Contacts app, there are multiple tabs (2 in my case). For the phone UI, they're managed by a ViewPager, with a fragment for each tab.
But for the tablet UI, each tab is an activity, rather than a fragment. They have to be, because you can't put fragments inside fragments. (Right?)
I realize I could just call setContentView() on the tab listener, but wouldn't that destroy the activity every time it was changed? I'm confused by a lot of this.
What's the best way to do this without breaking my phone UI?
A well designed tabbed UI never uses Activities for tab content.
You're correct in that you cannot nest Fragments in the current implementation, but that doesn't mean your only alternative is Activities. Tabs should always act as a view switch; a tab switch never creates navigation history and tab navigation should always happen within the same Activity.
Remember that Activities and Fragments are just controllers from an MVC point of view. They exist to respond to lifecycle events and manage elements of your application in response to those events, including views within your UI. The content of your UI is wholly determined by the view hierarchy of the current window and you can manipulate the view hierarchy in whatever way makes sense for your app. (While preferably still following the design guidelines!)
Since Fragments have a built-in mechanism for managing a view sub-hierarchy they're often a natural choice for factoring your UI but they're not the only way. ViewPager PagerAdapters can manipulate view sub-hierarchies by inflating them from the resource system, recycling views the way a ListView does, or any other mechanism you can come up with and not use Fragments at all if the lifecycle events they provide aren't needed. Different layout resources may include or exclude certain elements based on screen size using different layout variants for different resource qualifiers.
In short, don't get stuck on the idea that Fragments are the only way to do multi-pane UIs, or the only way to implement each page of a ViewPager. They're powerful options for both, but depending on the information architecture of your Activity you may find yourself using them in a different way than another app and that's OK.
Overall, if you're having trouble determining where the logical cut points are when factoring your Activity's UI, you may be building an overall UI for your app that is going to be as awkward to use as it is to implement. Let the UI design guide your implementation. If each tab is naturally switching out the entire content of the Activity window, then each tab might be well suited to a Fragment. Perhaps those Fragments in tablet mode expand their capabilities and present more than one pane in their respective layouts using different layout resources.