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

Summary

  • 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.

Conclusion

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 With Android Studio

Contents

  1. Getting Started With Android Studio
  2. The Activity And The UI
  3. Building The UI and a Calculator App
  4. Lifecycle and State
  5. Basic Controls And Events
  6. Spinners
  7. Pickers
  8. UI Graphics A Deep Dive
  9. Introducing Fragments
  10. Fragments and XML
  11. Fragment And Activity Working Together
  12. Managing Fragments
  13. Custom dialogs using DialogFragment
  14. Dialog Classes In DialogFragment

Androidgears

 

 

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 ( Friday, 20 June 2014 )
 
 

   
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.