Introducing Android Fragments
Introducing Android Fragments
Written by Mike James   
Thursday, 13 February 2014
Article Index
Introducing Android Fragments
Using a Fragment
The Activity
Summary and Conclusion


  • A Fragment is a class that implements the onCreateView method to supply a View hierarchy that can be displayed by an Activity.
  • To use a Fragment in an Activity you have to add it using a FragmentManager and a FragmentTransaction. You can add the Fragment using the add method but nothing happens until you call the commit method.
  • After the method that used the commit, usually the Activity's onCreate, terminates the CreateView event runs the Fragment's onCreateView and the Fragments View hierarchy is added to the Activity's content.  
  • A Fragment can be destroyed by the system and recreated from scratch automatically by having its onCreateView called. 
  • You have to write code to save and restore any additional state the Fragment may have.
  • If a task is common to all instances of the Fragment then its code should live in the Fragment. 
  • In particular the code to handle events can be defined within the Fragment.
  • The Activity should be used to host code that processes the data provided by the UI. 
  • Attaching Activity event handlers to the Fragment's UI or is difficult to do correctly. There is a better solution.


Next we need to look at how you can use Fragments with XML layouts and with Android Studio and the difficult problem of supporting pre-Honeycomb devices.

Meanwhile if you have any questions on what we've covered so far please let me know using the comments.

You can download the code for the programs from the CodeBin (note you have to register first).


Android Adventures - Mastering Fragments




  1. Introducing Fragments
  2. Fragments and XML
  3. Fragment And Activity Working Together
  4. Managing Fragments
  5. Custom dialogs using DialogFragment
  6. Dialog Classes In DialogFragment
  7. A NumberPicker DialogFragment Project
  8. ViewPager

If you are interested in creating custom template also see:

Custom Projects In Android Studio



To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter,FacebookGoogle+ or Linkedin,  or sign up for our weekly newsletter.


blog comments powered by Disqus



Last Updated ( Sunday, 26 July 2015 )

Copyright © 2016 All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.