What Is Fragment?

October 29, 2018 Amar Pal 0 Comments

What Is Fragment?

A fragment is an independent Android component which can be used by an activity. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. In this blog, we learn What Is Fragment? A fragment runs in the context of an activity, but has its own life cycle and typically its own user interface. It is also possible to define fragments without a user interface, i.e. headless fragments. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different layouts and their logic. You can build single-pane layouts for handsets (phones) and multi-pane layouts for tablets. You can also use fragments also to support different layout for landscape and portrait orientation on a smartphone.

Fragment Life Cycle

 

lifecylefragment

 

 

  • onAttach() :-The fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work.

 

  • onCreate() :- The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.

 

  • onCreateView() :-The system calls this callback when it’s time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment’s layout.
  • onActivityCreated() :-The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method.
  • onStart() :-The onStart() method is called once the fragment gets visible.

 

  • onResume() :-Fragment becomes active.

 

  • onPause() :-The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.

 

  • onStop() :-Fragment going to be stopped by calling onStop().

 

  • onDestroyView() :-Fragment view will destroy after call this method.

 

  • onDestroy() :-onDestroy() called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform.

 

 

Leave a Reply:

Your email address will not be published. Required fields are marked *