I have a question about the correct logical use of fragments in Android. I know that it was designed to be used to improve tablet experience, but does this imply that fragments should generally ONLY be used for this purpose? Or would it be poor development practice to use fragments as a replacement for a custom compound View?
For example, I am writing an app to keep tally. When the score sheet is produced, it creates a "ScoreCell," a custom compound control, for each player in a ScrollView. What I want to do(but don't see how as a View) is handle internal OnClickListeners that are activated by the containing activity: each ScoreCell has a TextView for the players' name, which I want to long-press to startActivityForResult() to pop open an input dialog to change the name of the ScoreCell. But seeing as the method for OnActivityResult() is unavailable in a View, would it be correct for me to instead make each ScoreCell a fragment?
Here is a picture of the activity to help understand the logic of what I need/am confused about
There are many questions in here, let me go through them.
No fragments are not meant just for tablet experience, in general they allow you to create more modular and adaptable layouts (think classes). They are extremely helpful in tablet layouts/landscape, but also give you reusable components.
At the same time, a fragment is not the right choice here... It is much easier to use a listview, coupled with a custom cell layout. Instead of using another activity to display a dialog simply call new Dialog() and dialog.show(). An activity should only be used as a dialog if it will be used by the user by a long period of time and provides a new "activity" (action)
Items in a list should not each be their own fragment, no. You can pop up a dialog without creating an entire Activity. Take a look at the documentation on AlertDialogs and DialogFragments for your dialogs and you can get the result from that.
Related
I am a beginner in android development. I am currently reading about Fragments from developer.android.com and this showed up about DialogFragment:
DialogFragment
Displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog helper methods in the Activity
class, because you can incorporate a fragment dialog into the back
stack of fragments managed by the activity, allowing the user to
return to a dismissed fragment.
Can anybody explain this to me ? Thanks
The fragment is lightweight and easy to implement. You need to style your activity to display a dialog. First, you have to understand the difference between activity and fragment.
Activity:
Activities have been around for a very long time and are used to
construct a single screen of your application. When someone is using
your Android application, the views that the user sees and interacts
with are hosted and controlled by a single activity. Much of your code
lives in these Activity classes, and there will typically be one
activity visible on the screen at a time.
Fragment
Fragments are another type of controller class that allows us to
separate components of our applications into reusable pieces.
Fragments must be hosted by an activity and an activity can host one
or more fragments at a time. A simple fragment looks similar to an activity, but has different life
cycle callback methods.
One of the original goals of the fragment concept was to help developers make applications that provide different user experiences on phones and tablets.
The canonical example of fragment use is an email client. Let’s take a look at the Gmail app. When running on a phone, the Gmail app will display a list of the user’s emails. Tapping on one of these emails will transition the screen to showing the detail view for that particular email. This process is composed of two separate screens.
For your Question:
It is always better to use dialog fragment instead of Activity. Because fragments are more customizable and easy to use. Light weight and gives reusability.
You can know more here:
http://www.informit.com/articles/article.aspx?p=2126865
Surprisingly, I couldn't find any posts regarding this, so here we go:
Why would I want to use a DialogFragment over a simple Fragment in Android? What advantages does the DialogFragment have that I will miss out on if I just use a regular Fragment?
Might be worth mentioning that I intend to have a fully customized view inside it...
Thanks!
A DialogFragment is no other than a Fragment that looks and acts like a Dialog would. So whether or not you want to use it is entirely depended on what do you want to make out of it.
From my experience using DialogFragment, I tend to utilize it as a "detailed" view of a list item. The one that hovers on the list instead of covering it entirely (like a normal Fragment would) so that the user doesn't lose context.
So that's that; you might want to use it wherever you want to show a view which either depend or need to retain its' parent context.
p.s., Yes, you can even put a fully customized view in a DialogFragment.
Well, basically you have all features od a Dialog in a fragment.
For example the back is handled by the system, you can dismiss the dialog clicking outside the dialog view, you can set the dialog to be not cancellable. And yes, the look and feel is the same of the other dialogs.
This question already has answers here:
Dilemma: when to use Fragments vs Activities:
(17 answers)
Closed 4 years ago.
I often need the different parts of my applications to have their own special behavior and UI, and I don't know how fragments can help. In most cases, I think it is quicker to create 2 different activities (e.g., 1 for tablets and 1 for handsets), and to share the common behaviors and events in a third class.
So, keeping this in mind, why should I use fragments ?
Fragments are more of a UI benefit in my opinion. It's convenient for the user sometimes to see two different views of two different classes on the same screen. If, in your moment of creativity, you decide it would be nice to display your application with, say, a listView that takes up half the screen and a webView that takes up the other half - so that when you click on a list item in fragment A it passes an intent to the webView in fragment B, and suddenly you see what you just clicked without the app switching activities - then you could use a fragment. That's just an example I came up with off the top of my head.
Bottom line: Fragments are two or more activities on the screen at the same time.
The benefits I see when using fragments are:
Encapsulation of logic.
Better handle of the lifecycle of the fragment.
Reusable in other activities.
The drawbacks I see are:
More code(For example, instantiating a fragment manager, adding the fragment transaction, writing the callbacks of the fragment)
Communication between fragments and activities is harder. As #jonney said it, you would need to deal with a parcelable interface to serialize your objects you wish to pass.
So, when deciding to use a fragment, I would ask myself the following questions:
Is the lifecycle of the fragment different from the activity's lifecycle?
If the lifecycle is different, you get better handling of the lifecycle using a fragment. For example, if you want to destroy the fragment, but not the activity. Such is the case, when you have a pager adapter.
Is the fragment going to be used in several activities?
The user input events will be reusable if you use a fragment.
Is the amount of communication between the fragment and the activity small?
If you need to pass big objects to the fragment, you would need to deal with the code that serializes them. Also, if you need to communicate between fragment and activity, you would probably need to implement interfaces. This, in most cases, adds complexity to your codebase. It's not a difference maker, but a criteria to take into account.
Google advises you to ALWAYS use Fragments.
Why? It's simple:
In the simplest case, Fragments are used like containers of activities.
Why do you need this? Again, it's simple.
Android 4 (ICS) supports both Smartphones and Tablets. This means the SAME application will be running on a smartphone and a tablet and they are likely to be very different.
Tablets have big screens which will be empty or unused - unless you assign it properly.
That means- Putting two fragments on one activity like Contact List and Contact Info.
The smatphone will display contact List, and on a touch- display the contact's Info.
On a tablet, the user will still see the list and the info will be next to it.
2 fragments- on one screen....
Smart? yes... supposed to be back compatible down to Android 1.6......
#############################################################
O.K, Already Knew That? then - just try to understand the case solved:
A lot of things work that way- list & details, Menus and Sub-Menus, Info, Detailed Info and some more detailed info.
You want a way to keep it natural and smooth for a tablet which you expect to preform that way, but can't expect smartphone to display it all like the tablet did...
Get it?
for more Information, check out this.
I really think you just need to catch the concept....
Historically each screen in an Android app was implemented as a separate Activity. This creates a challenge in passing information between screens because the Android Intent mechanism does not allow passing a reference type (i.e. object) directly between Activities. Instead the object must be serialized or a globally accessible reference made available.
By making each screen a separate Fragment, this data passing headache is completely avoided. Fragments always exist within the context of a given Activity and can always access that Activity. By storing the information of interest within the Activity, the Fragment for each screen can simply access the object reference through the Activity.
https://softwareengineering.stackexchange.com/questions/244771/why-use-android-fragments
Fragment primary support more dynamic & Large UI Screen like Tablet.Because Tablet screen is much larger than normal Handset. There is more room to combine & Interchange UI Component.
Fragment allow such design without the need for such complex change in the View hierarchy.
By divide activity layout in fragment, we become able to modify activity's appearance at runtime
I have a very simple 2 screen android app.
Is there any downside to simply switching out the layouts via setContentView or should i be using intents?Don't want to bugger up my app if something is wrong with this.
Another thing to consider is that activities form a stack. If you want to be able to go back to the previous activity via the 'back' button, then you need to use activity. But if it is something simple like a 'loading' screen when your app starts and you don't have to go back to it again, setting content view would be a much better idea.
Well as stated on Android Dev http://developer.android.com/reference/android/content/Intent.html
An Intent provides a facility for
performing late runtime binding
between the code in different
applications. Its most significant use
is in the launching of activities,
where it can be thought of as the glue
between activities. It is basically a
passive data structure holding an
abstract description of an action to
be performed.
Therefore if your two screens are 2 different applications I would say you want to simply use setContentView.
it will simplify your code when you want to pass info from one to the other views
There is nothing wrong with having two views in a single activity. This approach is more light-weight, as you don't need to go through the phase of stopping one activity and then starting another one. However, it will make your activity code bulkier. Consider now if you are going to need more functionality or more views in the future and if the answer is yes, then it would be better to create separate activities.
If the view is light-weight (a bunch of text boxes), then it should not matter. On the other hand, if the two screens are largely independent and heavy, you could use two different activities. The primary advantages with this approach are:
If there is an error in the second screen (an activity in this case), your application will fall back to the first screen whereas in the case of using the view, the whole application crashes
Better readability
Easier to add more functionality in the future
I was in the midsts of tinkering in android with the goal of trying to make this small exploration game. I actually got pretty far so far: a nice sprite system, a title screen with a main menu that is all in game code (no UI buttons or anything) that launch various activities. An activity that loads this cool map view, that when clicked on will load up another view of a more detailed "zoomed in" action part of a map. It all works pretty well but now I am left wondering how well I am going about this.
(What happens to a view when you instantiate and then move the set the context to a new view? I am guessing as long as the activity is alive all the instantiations of various views that an activity uses are still good? And in an activities onPause is when id have to save the data thats changed in these views to persist the state in the event the user quits the game etc.. ?)
I have three menu options at the start of the game. The main one is:
New Game
The new game, I launch my main map
activity that can launch three views:
First two are a loading screen for
the second, a map screen.
Third view is a more detailed action
orientated part that uses this sprite
engine I developed.
It all works pretty good as in the map view you click on a cell it tells the Calling Activity through a listener to start the detailed action view, and passes in the ID of the cell (so it knows what objects to load in the detailed view based on the cell clicked in second view). (This took me awhile to figure out but someone helped here on another question to get this.) Reference that helped me on this part here. I also used the various information here on ViewSwitcher.
I got even a yes no dialog box in the second view that asks if they really wanna goto that cell when they click on it, a yes tells the calling activity to set the new view. What helped me to get this working was this reference here. I also had to fiddle with the calls to getContext and that, I am still not 100% sure what getResources and getContext do for me.
So is it bad practice to call and load a dialog from a view? If it is, then I don't understand how if I have an event in the view that needs to pop up a dialog how I do that? Call back to the activity and let the activity handle it the dialog response and then call a method on the view for the response?
So far all this works great, I did have a bit to learn about threads too. I spawn a different thread for my MenuView (handles the detection of button clicks and responses), my CellMap view which handles the cool big map that users can click on to see the indepth view which is my SystemView view.
So basically the activity call list is like this:
Home.Activity -> ScrollMap.activity which listens to CellMap wher ethe Yes/No dialog apperas (in the view of CellMap) and if the answer is yes to the question, then the onTouchEvent starts up the SystemView view using
private CellMap.MapClickedListener onTouchEvent=
new CellMap.MapClickedListener() {
#Override
public void onMapClick(int id) {
setContentView(new SolarSystem(theContext,id));
}
};
To help anyone else, that listener had to be defined in my CellMap class. Then in the ScrollMap activity when I am about to start the CellMap I just call a method to CellMap sets the map click listener. So far this is the only way I have been able to get data from a dialog (in this case a it was clicked so set the new view) back to the calling activity. Is this proper practice?
Now my biggest question is, I have a playerObject class I want to initialize on new game event (I know how to detect that push) and that then is available to any view in any activity for the life time of the cycle. So far the game activity has just two (3 if you count the loading progress bar) views. I want to get the players name, is that another activity or view? I cannot find a decent tutorial of just how to make a simple input dialogg box that would return a string.
How do i go about passing this stuff around? After I get the players name from wherever that edit box is to be loaded, I want to set the players name in the class and pass that class instance off to another view or activity so they may get at that data. Everything I have searched on this seemed like overkill or not the right way. Whats the best way to pass this "playerClass" around so that I can access it from other views (to say display the players name in every view).
I also have my Home Activity that waits for an onClick on 3 buttons, it then launches their activity that shows the view. I realize a continue game and new game are the same activity and will just change in data loaded off the drive to restore a save game. When the new game button is clicked I would love to get the players name they want to use and of course set the member of the playerClass to this name so it persists.
Where do I call (an edit dialog is it?) the edit dialog from? (more over how do I build one that can take an okay button and input from keyboard etc). Id also like to make it pretty, maybe I could have a simple view that has one edit box in it and a nice image background (though I haven't figured out how to place the edit boxes to fit nicely matching a background i draw for it. I guess id like an edit dialog I can skin to look how i want it to and fit the look of the game).
I am actually kinda happy what I got so far its looking not to bad, just not sure about some specifics like getting user input for a name of the player. Storing that information and passing it then to other activities and views.
Is it better to have one GameMain activity, and a ton of views:
Map view
Character sheet view
inventory view etc etc?
Or Should there be diff activities in there somewhere as well?
You've written a lot here, so I'm go gonna go ahead and answer the questions I think you're asking.
First, how can one share information between activities and views? If you're just sharing it between views in a single activity, store it in the instance of the Activity subclass.
Sharing between activities requires a little bit more. Instead of using an instance of the default Application class, you can create a subclass of Application and use that instead. Put your data in fields of that subclass. To tell your app to use your subclass, modify the app manifest like so:
<application
....
android:name=".YourAppClassNameHere">
....
</application>
As for getting user input, the simple answer is use the built-in EditText view. since you seem to want to give your game a more "custom" style, though, you may need to go about creating your own editable textbox. That and buttons should allow for most sorts of basic user input.
Now, good practice vis-a-vis activities and views. I'm not aware of a standard for this, but when designing I generally try to think of activities as more conceptually separate elements, whereas views are conceptually interwoven. the line between the two is dependent, in part, on the scope of the app; an app with a narrow focus can afford to break more actions down into different activities than can one with a much broader focus.
Your "GameMain" example is a bit on the fence, but I think you've made the right choice: the activity is "playing the game," as opposed to a menu or high-scores table, and the views present different aspects of the game being played.