Why fragments, and when to use fragments instead of activities?
Not sure what video(s) you are referring to, but I doubt they are saying you should use fragments instead of activities, because they are not directly interchangeable. There is actually a fairly detailed entry in the Dev Guide, consider reading it for details.
In short, fragments live inside activities, and each activity can host many fragments. Like activities, they have a specific lifecycle, unlike activities, they are not top-level application components. Advantages of fragments include code reuse and modularity (e.g., using the same list view in many activities), including the ability to build multi-pane interfaces (mostly useful on tablets). The main disadvantage is (some) added complexity. You can generally achieve the same thing with (custom) views in a non-standard and less robust way.
#1 & #2 what are the purposes of using a fragment & what are the advantages and disadvantages of using fragments compared to using activities/views/layouts?
Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up. Let me elaborate;
The
ActionBar
. If you want tabs up there to navigate your app, you quickly see thatActionBar.TabListener
interface gives you aFragmentTransaction
as an input argument to theonTabSelected
method. You could probably ignore this, and do something else and clever, but you'd be working against the API, not with it.The
FragmentManager
handles «back» for you in a very clever way. Back does not mean back to the last activity, like for regular activities. It means back to the previous fragment state.You can use the cool
ViewPager
with aFragmentPagerAdapter
to create swipe interfaces. TheFragmentPagerAdapter
code is much cleaner than a regular adapter, and it controls instantiations of the individual fragments.Your life will be a lot easier if you use Fragments when you try to create applications for both phones and tablets. Since the fragments are so tied in with the Honeycomb+ APIs, you will want to use them on phones as well to reuse code. That's where the compatibility library comes in handy.
You even could and should use fragments for apps meant for phones only. If you have portability in mind. I use
ActionBarSherlock
and the compatibility libraries to create "ICS looking" apps, that look the same all the way back to version 1.6. You get the latest features like theActionBar
, with tabs, overflow, split action bar, viewpager etc.
Bonus 2
The best way to communicate between fragments are intents. When you press something in a Fragment you would typically call StartActivity()
with data on it. The intent is passed on to all fragments of the activity you launch.