I am trying to make a sudoku application. It's a fragment based design, in which a fragment hosts a custom view which is a board. I am trying to learn how to build an effective communication within FragmentActivity, Fragment and View
Although a view is created using the FragmentActivity context and I can catch a reference to that context within the current view and then call methods inside FragmentActivity I don't want to tie views so directly to a fragment activity. Instead I want to tie the view to use methods inside a fragment. How can i do that, I can I capture a reference to a fragment and call methods inside that fragment from a view?
First of all, I strongly recommend that you read through the documentation on Fragments, as you clearly don't understand the whole concept/purpose of using Fragments in the first place (which is OK, because they are confusing the first time you learn them :P).
A lot of your question doesn't make very much sense to me, because I'm not sure what the View you are speaking of refers to. What I can tell you is that Fragments have their own UI/layout, along with their own separate lifecycle. So it sounds like you don't want your FragmentActivity to interact with the Fragments layouts/methods at all... instead, you should implement the UI's behavior and layout inside of the Fragment itself. That is, the Fragment will be in charge of updating the UI, receiving click/touch events, displaying information on the screen etc. The FragmentActivity will simply hold a reference to the current Fragment(s), and will be in charge of displaying/swapping in and out new Fragments as necessary (via the activity's FragmentManager).
Hope that answers the question somewhat... read through the documentation a couple times, it sounds like you are just misunderstanding the theory/purpose behind Fragments.
Related
I know that fragments are used for making flexible UIs. But I was once asked that what is the advantage of using fragment over layout inflation. In other words we can inflate our custom layout file(one that we inflate for representing fragment UI) into the container layout of the backing activity. So why to use fragments instead?
In my opinion fragments are used over layout inflation for better designing purpose as it has its own lifecycle methods. Can anyone give me a better answer for this.
Fragments intercept Activity's lifecycle events (onCreate(), onStart(), onResume(), etc). Because of it Fragments can save and resume their state and data when your Activity is destroyed and then recreated.
So you may not save the data of your UI, when a user rotate his phone. Fragment does it for you.
Also Fragments are useful when you want to separate your UI into some units.
And with Fragments you may create your own class that builds in Activity's lifecycle.
Of course you may do the same without Fragments, but I believe that Google developed Fragments in order to improve our life and increase efficiency of our working.
I have implemented ViewPager and number of Fragment as child, here every child override own onAttach, onCreateView, onViewCreated and setUserVisibleHint.
In my app navigation behaviour is random, it not be in sequence every time. Since page viewer perform caching to load extra child, and this is what my problem is. I am not sure exactly when I should initialise/release member of child class.
Required suggestion from you guys, will it be preferable to use PageViwer in this case or I should go with traditional activity flow for each of component.
ViewPager is typically used for move efficient horizontal item to item navigation. Typical use cases would be
Swiping through the related items (e.g. emails, images, songs of an album, etc.)
Swiping between the tabs
Swiping back-and-forth in a wizard-like activity
For more details you can read a section about Swipe Views Android Design pattern.
Regarding the lifecycle, it basically uses the same lifecycle as any other Fragment. The only difference is, that lifecycle methods can be called a bit later or earlier than you expect, because of fragment's caching ViewPager implements.
I am not sure exactly when I should initialise/release member of child class.
You should basically rely on two methods: onStart() and onStop(). In onStart() you create class members and initialize everything you want to. In onStop() method you should deinitialize everything and remove all listeners you set in onStart().
Method setUserVisibleHint() is used independently of onStart() or onStop(). You shoud better not initialize or destroy anything in there. You must not consider it to the a lifecycle method, because it's not. It's there just to give you a hint, that your fragment is visible to the user. Here you can start or stop animation, or request data update or perform similar tasks. This is the only purpose of this method.
Required suggestion from you guys, will it be preferable to use
PageViwer in this case or I should go with traditional activity flow
for each of component.
If your activity fits into one of the points mentioned about, I would suggest you to use ViewPager. Otherwise you might consider other options.
Update: Most likely you won't override onCreate() and onDestroy() lifecycle methods of a fragment very often. You will use onCreateView() and onDestroyView() methods instead. There you can implement so called static initialization, the initialization which doesn't change while a fragment is still alive. This is layout initialization and similar tasks.
ViewPager Usages
Screen slides are transitions between one entire screen to another and are common with UIs like setup wizards or slideshows.
If you have good knowledge in Fragment than ViewPager is right component for implements.
Because viewpager provide a place which you can add fragment runtime.
For eg.
If you want to use TabBar in your project than viewpager is right component for using. Because it's provide a place which you can add Fragment runtime. Tabbar is common in android application. It's provide lot of functionality inbuild we can use to add fragment runtime.
Facebook app using ViewPager to manage tab. Viewpager provide smoothness of your application.
You can Download example from this url and check your requirement fulfill or not
You can download the Example here
ViewPager
It is an widget
Allows the user to swipe left or right to see an entirely new screen.
Easy to show the user multiple tabs
Dynamically add and remove pages (or tabs) at anytime.
To Read More: http://architects.dzone.com/articles/android-tutorial-using
I've started developing Android apps and I am wondering which way is better in case of adding fragments to activity. Let's assume that view for activity contain always three fragments. They won't changed. Always be the same. Thus is it better to add them by tags or include them in the activity code?
And a second question issue:
Let's say I have activity with fragment which is a list. Then when I clicked on item I want to show new view. Can I then replace the list fragment with new completely different fragment? Even if the answer is yes then is it better than creating new activity?
Thanks for all replies
which way is better in case of adding fragments to activity
One approach is not necessarily 'better' than the other - they both serve their own purposes, as with any static vs. dynamic comparison.
For example, fragments declared in a layout cannot be given arguments using setArguments(). Such a fragment can also not be replaced by another fragment: if it's part of the layout, it'll always be there. Of course you can still show/hide the instance, but attempting to actually remove it through a FragmentTransaction will simply not work. Static elements are usually easier to work with though, because they have a well-defined lifetime and behaviour.
Regarding your second question: yes, that's very possible. Some developers build their app around a single Activity container, swapping out fragments as the user navigates its way through the content. In most cases, from a user's point of view, there is little difference between doing this or having multiple activities. The important thing to keep in mind is to choose an approach you're comfortable with, doesn't overly complicate things and takes advantage of the patterns explained in Implementing Effective 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 know there have been quite a few questions about this, however, I'm still struggling to understand what role the Activity class should play when implementing the traditional Model-View-Controller design pattern on Android?
My gut feel is that it should be the Controller, however that means a one-to-one relationship between UI screens (since you must have one Activity per screen) and controllers, which defeats the point of MVC's loose coupling between the different components.
You are right. The xml interfaces could be defined as the View and your other class working with data as the Model.
The activity receive all the events and user inputs from the View ,so, we can easily said that it is the Controller.
But let's be clear , it's not a perfect (does it really exist ?) MVC
Have a look to this question , and more specifically , the first comment of the accepted answer, it may be useful
Activities can make competent controllers and, with fragments, you can also implement hierarchical MVC. Most of making MVC work is up to the programmer, because even in the strictest frameworks you can still find ways to do crazy things.
Android does not have a good architecture and it does not follow the MVC design pattern.
The best way to conceptualize Activity in MVC is as a View (with some controller logic) because it gets destroyed every time that a configuration change happens, such as a screen rotation or locale change, losing all its state.
The controller in this case would be the Application object, because it is your bridge to access the view (Activity and its GUI components) from code outside the Activity context. You have to use singletons so that there is only one Application object at a given time, otherwise there will be one Application object per process.
The Application object is not a good place to store the Model because its life cycle is detached from that of the Activities. It can get destroyed and recreated at any point of an Activity's life cycle (while the application is in the background) without causing it to restart, and then all its variables and references not assigned inside its onCreate() method will become null.
The Model therefore has to be stored on a GUI-less, headless fragment with setRetainInstance(true), that is linked to an activity, and has to be re-attached to it every time the activity is recreated. You have to use a fragment manager to ensure you are recovering the retained fragment and not creating it anew. This is also the best place to run background tasks, though you can also run them in the Application object. Never run tasks on an Activity as they will get destroyed on configuration changes.
I think the confusion may come in with defining a view as XML and so the Activity is mistaken for being the view. It's not. You pass the view (your XML layout) into the Activity which will then inflate the views contained within the XML layout. Your activity also passes data (models) into your views (EditText, TextView, extended version of base views, etc).
If you really want MVC then you can achieve this simply by setting up your view in an XML layout, create a view object which extends from your root view (if it's a RelativeLayout extend from that). From there you add your accessor methods and different logic needed for that view and you can then add unit testing around that.
In the Activity you will no longer pass in the ID of the layout and will instead do something like this:
CustomView customView = new CustomView(...);
setContentView(customView);
...
Of course almost all apps won't do this and you really don't need to do this. Calling findViewById is enough to link to that view object and call on the methods it has. Which in my mind, is MVC.