Android Fragments: Building dynamic UI, Why to use Fragments?

Fragment is a UI entity attached to Activity. Fragments can be reused by attaching in different activities. Activity can have multiple fragments attached to it. Fragment must be attached to an activity and its lifecycle will depend on its host activity. Multiple fragments attached to host activity can be operated separately such as add or remove or replace them.  Fragments operations are managed by FragmentManager and each operation or task on activity is performed with FragmentTransanction. With Fragments you can perform better optimization for your application in order to adapt UI for phone as well as tablets.

 Lifecycle of a fragment

  1. onAttach(Activity) called once the fragment is associated with its activity.
  2. onCreate(Bundle) called to do initial creation of the fragment.
  3. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
  4. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate().
  5. onViewStateRestored(Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored.
  6. onStart() makes the fragment visible to the user (based on its containing activity being started).
  7. onResume() makes the fragment interacting with the user (based on its containing activity being resumed).

 As a fragment is no longer being used, it goes through a reverse series of callbacks:

  1. onPause() fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity.
  2. onStop() fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.
  3. onDestroyView() allows the fragment to clean up resources associated with its View.
  4. onDestroy() called to do final cleanup of the fragment’s state.
  5. onDetach() called immediately prior to the fragment no longer being associated with its activity.

Sample Fragment Application

Create a android project in Eclipse, Name your application an set package. I have used name SampleFragmentApplication and package name as com.androidsrc.fragment.

We will attach two fragments to main activity of application. One fragment will be of type ListFragment. ListFragment gives you combo of ListView and Fragment functionality which is very easy to use. In ListFragment, we will set adapter for colors in ListView. On clicking of item of this listview, we will interact with second fragment and set corresponding color to its ImageView.

Lets start with layout files. Modify your res/layout/actvity_main.xml as below

Create layout file for fragment one res/layout/fragment_one.xml as below

Create layout for your second fragment res/layout/fragment_two.xml as below

Now we are done with layout files. Lets move on to source files.
Inside your package, create two class files FragmentOne.java which will be extending ListFragment class and another FragmentTwo.java which will be extending Fragment class.

In FragmentOne.java, create a string array for colors and in onCreateView(), inflate layout file for this fragment and set adapter to ListView by creating a ArrayAdapter. Make sure to override onListItemClick() so that we can handle click events for list items. Since we want to set color for second fragment’s ImageView to same as item clicked, we find fragment by its id using FragmentManager and setImageViewBackground() with color value as parameter. This function we will define in FragmentTwo.java and update color.

For FragmentTwo.java, we will create a ImageView object which will be initialized while creating view for this fragment. Define setImageViewBackground() in order to set background of ImageView.

Finally, lets move on to MainActivity.java. Not much is required to edit here. Make sure we are calling setContentView().

Run your program. Try changing color of second fragment by clicking listview items from first fragment. Kudos we are done with sample fragment application. For refreshing up topic, Please refer below for its benefits and quick remember points.

 

Benefits of Fragments over Activity

1. Communication between various fragments is very easier than sending data back and forth between activities.

2. Re-usability – Fragments have very good re-usability. You can use same fragment over different places in your application.

3. UI Customizations – Its very easy to handle or implement functionalities like swipe between views or tab views.

4. Easy to handle state of UI over orientation change of device- Making setRetainInstance(true) will reattach previous fragments to the new instance of activity and retain their state.

Points to remember

  • A fragment has its own layout and its own behavior with its own life-cycle and callbacks.
  • You can add or remove fragments in an activity while the activity is running.
  • You can combine multiple fragments in a single activity to build a multi-pane UI.
  • A fragment can be used in multiple activities.
  • Fragment life cycle is closely related to the life-cycle of its host activity.
  • When the activity is paused, all the fragments available in the activity will also be stopped.
  • A fragment can implement a behavior that has no user interface component.

You may also like...