Deference between YouTubePlayerFragment and YouTubePlayerView - android

The demo project provided by google for using the Youtube API. which allow developers to include a youtube player inside there app. I noticed to demoes one is using YouTubePlayerView and the other used YouTubePlayerFragment. I can't really figure out the difference.
Maybe there is a technical difference. What is it?

Fragments:
"A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities)."
http://developer.android.com/guide/components/fragments.html
Views:
"This class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.). The ViewGroup subclass is the base class for layouts, which are invisible containers that hold other Views (or other ViewGroups) and define their layout properties."
http://developer.android.com/reference/android/view/View.html
What's the difference?
"So, the main reason to use Fragments are for the backstack and lifecycle features. Otherwise, custom views are more light weight, simpler to implement, and have the advantage that they can be nested."
What is the benefit of using Fragments in Android, rather than Views?
Hopefully this help clears things up.

Related

should i use a Fragment or an Activity for an ever present View in my Android App?

im developing an application with multiple screens using activities and fragments. The principle behind my decisions to use one or the other are based on the interaction in the application.
I have come to the conclusion that you should use an activity whenever major UI elements remain present after an event has occurred that forces the views inside the UI to change (An example of this can be a tabhost nested in the toolbar styled as the Google Play store android App with multiple fragments as childs. Another example is fragments representing the different rows or clickable elements on a navigation drawer).
So right now im presented with the dilemma of choosing once again between the two (fragment or activity) for a UI element that is going to be present across my whole application. Its triggered by a floating action button that launches a creation tool for an element inside my application and i needed to be accesible across all of my apps screens.
So to sum things up, what i need to know if its better to use a fragment or an activity for an element that is ever present across my whole application.
Thanks in advance
Use Fragments or a compound Views. But both in the right way.
Fragments are thought for reusable combinations of views. Compound Views are Layouts containing views. They are the right way if you want to create views from more primitive views, for example a View containing TextView and a increment- and decrement-button.
Fragments are more Activity-like. They have a real lifecycle. Your description looks like you want to create acitivity-parts. And thats exactly what fragments do.
A Fragment represents a behavior or a portion of user interface in an
Activity. You can combine multiple fragments in a single activity to
build a multi-pane UI and reuse a fragment in multiple activities.
Taken from Android SDK Documentation: Fragments.

Activities or Fragments in NavigationView?

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.

When would you reuse a fragment?

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.

Use View or Fragment in ViewPager

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.

Why use Fragments? [duplicate]

This question already has answers here:
What is the benefit of using Fragments in Android, rather than Views?
(6 answers)
Closed 10 years ago.
What is the advantage to using Fragments over using custom Views that are reused in different layouts?
In the original blog post introducing fragments, Dianne Hackborn says that
[Fragments] make it easier for developers to write applications that can scale
across a variety of screen sizes, beyond the facilities already
available in the platform.
and she goes on to explain Fragments in the context of making a tablet layout for an app that combines the UI of two activities from the phone version of the same app.
But it seems that the same reuse could be achieved using custom Views. The main different between Fragments and Views seems to be that they have differing lifecycles...
The Fragment lifecycle is:
onAttach(), onCreate(), onCreateView(), onActivityCreated(), onStart(), onResume(), onPause(), onStop(), onDestroyView(), onDestroy(), onDetatch().
The View lifecycle is:
ctor, onFinishInflate(), onAttachedToWindow(), onMeasure(), onLayout(), onDetatchedFromWindow()
I'd like to hear from developers with experience writing large apps about what benefits (if any) they've seen in using Fragments vs custom Views to divide up the UI into reusable pieces.
The main reason is that fragments are more reusable than custom views.
Sometimes you can't create a fully encapsulated UI component relying on views alone. This is because there are things you would want to put into your view but can't because only an Activity can handle them, thus forcing tight coupling between an Activity and a View.
Here is one such example. Lets say you want to create a reusable UI component that, among many things, want to capture a photo and do something with it. Traditionally you would fire an intent that starts the camera and returns with the captured image.
Notice that your custom UI component can't fully encapsulate this functionality because it will have to rely on hosting Activity's startActivityForResult because views don't accept activity results (they can indirectly fire an intent through context).
Now if you wanted to reuse your custom UI component in different activities you would be repeating the code for Activity.startActivityForResult.
Fragment on the other hand cleanly solve this problem.
Similarly your fragment can contribute items to your options menu, something traditionally only an Activity could do. Again this could be important if the state of your custom view dictates what goes in the menu.
A fragment is way more than just a view. In fact it can even be totally without a view. It can have all sorts of stuff in it including AsyncTasks, various Listeners, file and database access and so on and so on.
Think of it as a small activity, but you can have multiple of them on the screen and work with them all including communicating with each other while they are visible.
E.g. you could have a list of shopping cart displayed in one fragment and the currently selected cart in detail in another fragment. You then e.g. change the quantity of an item in the detail view and the list view could be notified about it and update the total price in the list view. You can totally orchestrate interactions like that nicely while e.g. still having only one of them visible on a smaller screen device.
I have refactored a large business app (>15 activities) from activities to fragments to get good tablet support and I would never start a new app without fragments.
Update Feb 2016: While the above still holds true, there are complexities with fragments that caused many people to entirely avoid using them. Newer patterns such as usage of MVC approaches and more powerful views provide alternatives. As they say .. YMMV.
Some description:
Imagine Activity as a plate that hold one big cake.
Fragment would be a container that slices the same cake into pieces.
Each slice contains it own logics (listeners, etc).
And in total they are almost no different with the one big cake.
The benefit:
When you plate can't hold a big cake. (Screen is small) You can easily use a a few plates (Activity) to hold each of them WITHOUT the need to move your logics into the new activity.
Better re-usability. I have some instances where I could reuse a fragment entirely in another App. You might claim that a custom view could does that too. But refer to point 1, I could reuse it with just few lines of layout changes but for a custom view, it have to find a way to plug it into both layout and code.
It is, in some sense, a more OO ways of organising your UI logics in Android programming. When you have a feature (A new partition on the screen for example), you create a new Fragment class, with minor modification to existing activity class. However if you are programming only with activity, you will need to add logics and make big modification on tested class.
Just my 2 cents. :)
The lifecycle methods are probably your biggest hint. If you think about it, they correlate closely to the activity lifecycle (with some hooks into the activity and views). In fact, in the article you linked, Hackborn says:
In some ways you can think of a Fragment as a mini-Activity
As with many things in software design/development, there are a multitude of ways to do things. There are many different places you could put your code. Yes, you could probably put a lot into a view, but keeping different concerns separated in different classes is a good thing though. The classic pattern of this is MVC and it applies in this scenario. You don't want to bake in too much controller logic into your view. It's better to keep it in controller-like classes which are the activity and now the fragment. This is why the fragment's lifecycle is more like the activity's than the view's--it was made to facilitate this kind of organization.
I touched Fragments once and found them not very useful (see this post). From what I have read, A Fragment is really a fancy word for an Object with access to Activity Context. I like to ignore Fragments in my work, and just create these Objects myself. I have created very large, very demanding apps by passing an Activity to constructors, instead of Context. One major benefit, however, for using Fragments is that they are supported by the View layout system - so you can easily add them to Android xml (if you use it for your layouts).
Custom views are much more work than just using fragments in place of your activities. if you decide to use Activities and custom Views, you have to create your custom view, and then you have to implement the same activity lifecycle methods in your activity (a very similar lifecycle is used for fragments).
Using Fragments also allows you to separate components into their own classes (Fragments), rather than having too much logic in a single Activity. Let me ground that with an example:
Say you're implementing a magazine reader application. using fragments, you could create a fragment: ArticleList, which displays a list of articles, and another fragment: ArticleDisplay, which handles the logic for displaying content. you can then specify how these fragments should interact using the fragments tools, so that on a handset, you can use the full screen real-estate for ArticleDisplay, while on a tablet, you can display the fragments side by side.
If you were to attempt this with an Activity/custom view, you'd have the logic for both Fragments in your monolithic Activity, you'd have to write a custom view, and you'd have to debug this unwieldy monster.
Fragments are, in general, a more sophisticated and powerful way to write your applications. They can do everything an Activity can do, and more. If you don't need the extra functionality, the defaults will probably get you where you need to go, and with less work.

Categories

Resources