I've been coding android apps for a couple of years now and when I started fragments was the way to go so I've been using them since.
From the beginning I thought the lifecycle and handling of fragments was a mess and tried a couple of different approaches with a single activity or 1 activity per groups of fragments etc.
I was more comfortable with the single activity approach but then ran into problem where to show and hide fragments etc.
I tried to have all logic for showing/hiding a fragment in its own class and then using a model-notifier pattern for pushing out a message containing information about which fragment to show and hide. The last thing I tried was to have a "FragmentService" that gets notified, using EventBus, with a message (DTO) containing information about what fragment to show/hide and a bundle to pass with it.
I'm not totally satisfied with my architecture for managing fragment yet so now I'm curious how you solve this problems? I want every fragment to be loosely coupled from each other and able to start Fragment1 from Fragment2, 3 or 4 etc.
Can this be solved in a centralized and understandable way?
Related
The idea of using MVVM is that view observes ViewModelchanges and acts. I'm using an Activity which uses 7 Fragments and the navigation between them goes through observing individual changes in the Activity from different Fragments and launching/replacing Fragments accordingly. For instance,Fragment L calls setValue, then as a result the main Activity receives the event and switches to Fragment M and Fragment M calls getValue from the observed MutableLiveData and not directly functioning as a listener to changes. Does that the right structure or should each Fragment observe changes by himself ? What would the right way to handle multiple navigations between multiple Fragments
I don't see anything wrong in what you just said. Fragments should be independent from each other unless they are nested.
If you need communication between fragments that can be done in many ways. The most basic way is to do that through activity. Activity knows how its fragments interact with each other, but fragments remain independent. They can listen to events, no problem here, but make sure you have a 'rule' in your project about how you handle events.
E.g. I prefer having one listener at a time to have the order more predictable. If I want multiple fragments to handle the event, I usually place the handler in the activity and then pass the event to fragments in the exact order I need. Otherwise it might quickly get out of control.
There are other ways too, such as EventBus, BroadcastReceivers or any other event-based mechanism.
I hope that helps. If I didn't answer your question then to answer it more precisely I'd need the question to be more specific.
As the title states, does it considered as a good practice to use a single fragment within an activity to display the content? I began to notice that more and more developers start to use the fragment as an insulation layer to separate the lifecycle logic from UI that activity (sorry, fragment) displays. The most recent example that I stumble on is the architecture blueprints provided by Google developers. They use just one single fragment for UI while the activity handles ViewModel and all the navigation between screens.
So, is this a good practice or just a personal preference? Would you care to share your opinion on the subject?
Using Fragments as your UI is a good practice.
Activity can hold all common logic, while you can use different fragments to show different UI for mobile vs tablet.
If the UI is in Fragment, you can reuse it in multiple activities.
If you have a workflow scenario like Registration flow, using a single activity with multiple fragments will help you out a lot.
Manipulation of fragment backstack is a lot easier than trying to do the same with activities.
Use fragment for display the UI is good,Reason is listed below:-
1.You can create one activity,and display multiple fragment inside that activity.
2.Handling back press is easy as you can override onBackpress() in main activity class and handle back key event from fragment(s) as check its(fragment) visibility and handle event.
3. Reusability of layout.
4. Reusability of fragment.
5. Handling different action menu is very easy for different fragment(s).
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.
I am planning an app and trying to explore all the possible development options/methods I have available. One thing I'm struggling to get my head around is Fragments. I see a lot of people praising them as you can "resuse" fragments throughout the app but I can't think of an example situation.
From some example apps I have looked at (all been tabular layouts) the code for each fragment has one layout, so why not have a seperate activity instead?
I am hoping to implement a tabular layout in my app. If anyone can give me an example of a fragment being reused within an app I hope it will give me a better understanding of the benefits.
"Reuse" is overrated. Of course - you can put this same fragment (with this same features) in different places of your application - let's say that you can use a fragment in different, horizontal and vertical layouts (as you probably saw in Google's tutorial).
But at the end using fragments simplifies your project - for example - you can switch fragments inside one activity and get benefits of much easier navigation and in app communication.
Using fragments gives you one more thing - flexibility. It's much easier to move some view from one place to another, or just remove from application. All that because fragment encapsulates logic and usually a view, still offering power of externally managed lifecycle.
(Thanks for comment from Richard Le Mesurier)
Fragment is not a View neither a ViewGroup. It is not a visual element at all. Fragment inherits directly from Object.
One should think of a Fragment as a unity of a reusable code, reusable in various Activities (the Activities consist of visible elements).
Thus if you can think of any code you can reuse through several Activities (even the same Activity with different layout) and that code somehow depends on Activity lifecycle, then you probably should make this code a Fragment.
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.