Introduction about Fragments and their intercommunication mechanism
void onActivityCreated(Bundle savedInstanceState) // Called when the fragment's activity has been created and this fragment's view hierarchy instantiated.
void onActivityResult(int requestCode, int resultCode, Intent data) // Receive the result from a previous call to startActivityForResult(Intent, int).
void onAttach(Activity activity) // This method was deprecated in API level 23. Use onAttach(Context) instead.
void onAttach(Context context) // Called when a fragment is first attached to its context.
void onAttachFragment(Fragment childFragment) // Called when a fragment is attached as a child of this fragment.
void onConfigurationChanged(Configuration newConfig) // Called by the system when the device configuration changes while your component is running.
void onCreate(Bundle savedInstanceState) // Called to do initial creation of a fragment.
View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) // Called to have the fragment instantiate its user interface view.
void onDestroy() // Called when the fragment is no longer in use.
void onDestroyView() // Called when the view previously created by onCreateView(LayoutInflater, ViewGroup, Bundle) has been detached from the fragment.
void onDetach() // Called when the fragment is no longer attached to its activity.
void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) // This method was deprecated in API level 23. Use onInflate(Context, AttributeSet, Bundle) instead.
void onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState) // Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity.
void onPause() // Called when the Fragment is no longer resumed.
void onResume() // Called when the fragment is visible to the user and actively running.
void onSaveInstanceState(Bundle outState) // Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance of its process is restarted.
void onStart() // Called when the Fragment is visible to the user.
void onStop() // Called when the Fragment is no longer started.
void onViewStateRestored(Bundle savedInstanceState) // Called when all saved state has been restored into the view hierarchy of the fragment.
A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).
Every fragment must have an empty constructor, so it can be instantiated when restoring its activity's state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments().
Animate the transition between fragments
To animate the transition between fragments, or to animate the process of showing or hiding a fragment you use the FragmentManager to create a FragmentTransaction.
For a single FragmentTransaction, there are two different ways to perform animations: you can use a standard animation or you can supply your own custom animations.
Standard animations are specified by calling FragmentTransaction.setTransition(int transit), and using one of the pre-defined constants available in the FragmentTransaction class. At the time of writing, these constants are:
The complete transaction might look something like this:
Custom animations are specified by calling either FragmentTransaction.setCustomAnimations(int enter, int exit) or FragmentTransaction.setCustomAnimations(int enter, int exit, int popEnter, int popExit).
The enter and exit animations will be played for FragmentTransactions that do not involve popping fragments off of the back stack. The popEnter and popExit animations will be played when popping a fragment off of the back stack.
The following code shows how you would replace a fragment by sliding out one fragment and sliding the other one in it's place.
The XML animation definitions would use the objectAnimator tag. An example of slide_in_left.xml might look something like this:
Communication between Fragments
All communications between Fragments must go via an Activity. Fragments CANNOT communicate with each other without an Activity.
In this sample, we have a MainActivity that hosts two fragments, SenderFragment and ReceiverFragment, for sending and receiving a message (a simple String in this case) respectively.
A Button in SenderFragment initiates the process of sending the message. A TextView in the ReceiverFragment is updated when the message is received by it.
Following is the snippet for the MainActivity with comments explaining the important lines of code:
The layout file for the MainActivity hosts two fragments inside a LinearLayout :
The SenderFragment exposes an interface SendMessageListener that helps the MainActivity know when Button in the SenderFragment was clicked.
Following is the code snippet for the SenderFragment explaining the important lines of code:
The layout file for the SenderFragment:
The ReceiverFragment is simple and exposes a simple public method to updates its TextView. When the MainActivity receives the message from the SenderFragment it calls this public method of the ReceiverFragment
Following is the code snippet for the ReceiverFragment with comments explaining the important lines of code :
The layout file for the ReceiverFragment :
Navigation between fragments using backstack and static fabric pattern
First of all, we need to add our first Fragment at the beginning, we should do it in the onCreate() method of our Activity:
Next, we need to manage our backstack. The easiest way is using a function added in our activity that is used for all FragmentTransactions.
Finally, we should override onBackPressed() to exit the application when going back from the last Fragment available in the backstack.
Execution in activity:
Execution outside activity (assuming MainActivity is our activity):
Pass data from Activity to Fragment using Bundle
All fragments should have an empty constructor (i.e. a constructor method having no input arguments). Therefore, in order to pass your data to the Fragment being created, you should use the setArguments() method. This methods gets a bundle, which you store your data in, and stores the Bundle in the arguments. Subsequently, this Bundle can then be retrieved in onCreate() and onCreateView() call backs of the Fragment.
Sending events back to an activity with callback interface
If you need to send events from fragment to activity, one of the possible solutions is to define callback interface and require that the host activity implement it.
Send callback to an activity, when fragment's button clicked
First of all, define callback interface:
Next step is to assign this callback in fragment:
And finally, implement callback in activity:
The newInstance() pattern
Although it is possible to create a fragment constructor with parameters, Android internally calls the zero-argument constructor when recreating fragments (for example, if they are being restored after being killed for Android's own reasons). For this reason, it is not advisable to rely on a constructor that has parameters.
To ensure that your expected fragment arguments are always present you can use a static newInstance() method to create the fragment, and put whatever parameters you want in to a bundle that will be available when creating a new instance.
Now, in the Activity:
This pattern is a best practice to ensure that all the needed arguments will be passed to fragments on creation.
Note that when the system destroys the fragment and re-creates it later, it will automatically restore its state - but you must provide it with an onSaveInstanceState(Bundle) implementation.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0