IT. Expert System.

Android Reference


Class Fragment

  • All Implemented Interfaces:
    ComponentCallbacks, ComponentCallbacks2, View.OnCreateContextMenuListener
    Direct Known Subclasses:
    DialogFragment, ListFragment, PreferenceFragment, WebViewFragment

    public class Fragment
    extends Object
    implements ComponentCallbacks2, View.OnCreateContextMenuListener
    A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity. Interaction with fragments is done through FragmentManager, which can be obtained via Activity.getFragmentManager() and Fragment.getFragmentManager().

    The Fragment class can be used many ways to achieve a wide variety of results. In its core, it represents a particular operation or interface that is running within a larger Activity. A Fragment is closely tied to the Activity it is in, and can not be used apart from one. Though Fragment defines its own lifecycle, that lifecycle is dependent on its activity: if the activity is stopped, no fragments inside of it can be started; when the activity is destroyed, all fragments will be destroyed.

    All subclasses of Fragment must include a public empty constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the empty constructor is not available, a runtime exception will occur in some cases during state restore.

    Topics covered here:

    1. Older Platforms
    2. Lifecycle
    3. Layout
    4. Back Stack

    Developer Guides

    For more information about using fragments, read the Fragments developer guide.

    Older Platforms

    While the Fragment API was introduced in Build.VERSION_CODES.HONEYCOMB, a version of the API at is also available for use on older platforms through FragmentActivity. See the blog post Fragments For All for more details.


    Though a Fragment's lifecycle is tied to its owning activity, it has its own wrinkle on the standard activity lifecycle. It includes basic activity lifecycle methods such as onResume(), but also important are methods related to interactions with the activity and UI generation.

    The core series of lifecycle methods that are called to bring a fragment up to resumed state (interacting with the user) are:

    1. onAttach( called once the fragment is associated with its activity.
    2. onCreate(android.os.Bundle) called to do initial creation of the fragment.
    3. onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) creates and returns the view hierarchy associated with the fragment.
    4. onActivityCreated(android.os.Bundle) tells the fragment that its activity has completed its own Activity.onCreate().
    5. onViewStateRestored(android.os.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.


    Fragments can be used as part of your application's layout, allowing you to better modularize your code and more easily adjust your user interface to the screen it is running on. As an example, we can look at a simple program consisting of a list of items, and display of the details of each item.

    An activity's layout XML can include <fragment> tags to embed fragment instances inside of the layout. For example, here is a simple layout that embeds one fragment:

    The layout is installed in the activity in the normal way:

    The titles fragment, showing a list of titles, is fairly simple, relying on ListFragment for most of its work. Note the implementation of clicking an item: depending on the current activity's layout, it can either create and display a new fragment to show the details in-place (more about this later), or start a new activity to show the details.

    The details fragment showing the contents of a selected item just displays a string of text based on an index of a string array built in to the app:

    In this case when the user clicks on a title, there is no details container in the current activity, so the titles fragment's click code will launch a new activity to display the details fragment:

    However the screen may be large enough to show both the list of titles and details about the currently selected title. To use such a layout on a landscape screen, this alternative layout can be placed under layout-land:

    Note how the prior code will adjust to this alternative UI flow: the titles fragment will now embed the details fragment inside of this activity, and the details activity will finish itself if it is running in a configuration where the details can be shown in-place.

    When a configuration change causes the activity hosting these fragments to restart, its new instance may use a different layout that doesn't include the same fragments as the previous layout. In this case all of the previous fragments will still be instantiated and running in the new instance. However, any that are no longer associated with a <fragment> tag in the view hierarchy will not have their content view created and will return false from isInLayout(). (The code here also shows how you can determine if a fragment placed in a container is no longer running in a layout with that container and avoid creating its view hierarchy in that case.)

    The attributes of the <fragment> tag are used to control the LayoutParams provided when attaching the fragment's view to the parent container. They can also be parsed by the fragment in onInflate(android.util.AttributeSet, android.os.Bundle) as parameters.

    The fragment being instantiated must have some kind of unique identifier so that it can be re-associated with a previous instance if the parent activity needs to be destroyed and recreated. This can be provided these ways:

    • If nothing is explicitly supplied, the view ID of the container will be used.
    • android:tag can be used in <fragment> to provide a specific tag name for the fragment.
    • android:id can be used in <fragment> to provide a specific identifier for the fragment.

    Back Stack

    The transaction in which fragments are modified can be placed on an internal back-stack of the owning activity. When the user presses back in the activity, any transactions on the back stack are popped off before the activity itself is finished.

    For example, consider this simple fragment that is instantiated with an integer argument and displays that in a TextView in its UI:

    A function that creates a new instance of the fragment, replacing whatever current fragment instance is being shown and pushing that change on to the back stack could be written as:

    After each call to this function, a new entry is on the stack, and pressing back will pop it to return the user to whatever previous state the activity UI was in.

    • Constructor Detail

      • Fragment

        public Fragment()
        Default constructor. 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(android.os.Bundle) and later retrieved by the Fragment with getArguments().

        Applications should generally not implement a constructor. The first place application code an run where the fragment is ready to be used is in onAttach(Activity), the point where the fragment is actually associated with its activity. Some applications may also want to implement onInflate(android.util.AttributeSet, android.os.Bundle) to retrieve attributes from a layout resource, though should take care here because this happens for the fragment is attached to its activity.

    • Method Detail

      • instantiate

        public static Fragment instantiate(Context context,
                           String fname,
                           Bundle args)
        Create a new instance of a Fragment with the given class name. This is the same as calling its empty constructor.
        context - The calling context being used to instantiate the fragment. This is currently just used to get its ClassLoader.
        fname - The class name of the fragment to instantiate.
        args - Bundle of arguments to supply to the fragment, which it can retrieve with getArguments(). May be null.
        Returns a new fragment instance.
        InstantiationException - If there is a failure in instantiating the given fragment class. This is a runtime exception; it is not normally expected to happen.
      • equals

        public final boolean equals(Object o)
        Subclasses can not override equals().
        equals in class Object
        o - the object to compare this instance with.
        true if the specified object is equal to this Object; false otherwise.
        See Also:
      • toString

        public String toString()
        Description copied from class: Object
        Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:
           getClass().getName() + '@' + Integer.toHexString(hashCode())

        See Writing a useful toString method if you intend implementing your own toString method.

        toString in class Object
        a printable representation of this object.
      • getId

        public final int getId()
        Return the identifier this fragment is known by. This is either the android:id value supplied in a layout or the container view ID supplied when adding the fragment.
      • getTag

        public final String getTag()
        Get the tag name of the fragment, if specified.
      • setArguments

        public void setArguments(Bundle args)
        Supply the construction arguments for this fragment. This can only be called before the fragment has been attached to its activity; that is, you should call it immediately after constructing the fragment. The arguments supplied here will be retained across fragment destroy and creation.
      • getArguments

        public final Bundle getArguments()
        Return the arguments supplied when the fragment was instantiated, if any.
      • setInitialSavedState

        public void setInitialSavedState(Fragment.SavedState state)
        Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by FragmentManager.saveFragmentInstanceState.
        state - The state the fragment should be restored from.
      • setTargetFragment

        public void setTargetFragment(Fragment fragment,
                             int requestCode)
        Optional target for this fragment. This may be used, for example, if this fragment is being started by another, and when done wants to give a result back to the first. The target set here is retained across instances via FragmentManager.putFragment().
        fragment - The fragment that is the target of this one.
        requestCode - Optional request code, for convenience if you are going to call back with onActivityResult(int, int, Intent).
      • getActivity

        public final Activity getActivity()
        Return the Activity this fragment is currently associated with.
      • getResources

        public final Resources getResources()
        Return getActivity().getResources().
      • getText

        public final CharSequence getText(int resId)
        Return a localized, styled CharSequence from the application's package's default string table.
        resId - Resource id for the CharSequence text
      • getString

        public final String getString(int resId)
        Return a localized string from the application's package's default string table.
        resId - Resource id for the string
      • getString

        public final String getString(int resId,
                       Object... formatArgs)
        Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in Formatter and String.format(java.lang.String, java.lang.Object...).
        resId - Resource id for the format string
        formatArgs - The format arguments that will be used for substitution.
      • getFragmentManager

        public final FragmentManager getFragmentManager()
        Return the FragmentManager for interacting with fragments associated with this fragment's activity. Note that this will be non-null slightly before getActivity(), during the time from when the fragment is placed in a FragmentTransaction until it is committed and attached to its activity.

        If this Fragment is a child of another Fragment, the FragmentManager returned here will be the parent's getChildFragmentManager().

      • getChildFragmentManager

        public final FragmentManager getChildFragmentManager()
        Return a private FragmentManager for placing and managing Fragments inside of this Fragment.
      • getParentFragment

        public final Fragment getParentFragment()
        Returns the parent Fragment containing this Fragment. If this Fragment is attached directly to an Activity, returns null.
      • isAdded

        public final boolean isAdded()
        Return true if the fragment is currently added to its activity.
      • isDetached

        public final boolean isDetached()
        Return true if the fragment has been explicitly detached from the UI. That is, FragmentTransaction.detach(Fragment) has been used on it.
      • isRemoving

        public final boolean isRemoving()
        Return true if this fragment is currently being removed from its activity. This is not whether its activity is finishing, but rather whether it is in the process of being removed from its activity.
      • isInLayout

        public final boolean isInLayout()
        Return true if the layout is included as part of an activity view hierarchy via the <fragment> tag. This will always be true when fragments are created through the <fragment> tag, except in the case where an old fragment is restored from a previous state and it does not appear in the layout of the current state.
      • isResumed

        public final boolean isResumed()
        Return true if the fragment is in the resumed state. This is true for the duration of onResume() and onPause() as well.
      • isVisible

        public final boolean isVisible()
        Return true if the fragment is currently visible to the user. This means it: (1) has been added, (2) has its view attached to the window, and (3) is not hidden.
      • isHidden

        public final boolean isHidden()
        Return true if the fragment has been hidden. By default fragments are shown. You can find out about changes to this state with onHiddenChanged(boolean). Note that the hidden state is orthogonal to other states -- that is, to be visible to the user, a fragment must be both started and not hidden.
      • onHiddenChanged

        public void onHiddenChanged(boolean hidden)
        Called when the hidden state (as returned by isHidden() of the fragment has changed. Fragments start out not hidden; this will be called whenever the fragment changes state from that.
        hidden - True if the fragment is now hidden, false if it is not visible.
      • setRetainInstance

        public void setRetainInstance(boolean retain)
        Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated:
      • getRetainInstance

        public final boolean getRetainInstance()
      • setHasOptionsMenu

        public void setHasOptionsMenu(boolean hasMenu)
        Report that this fragment would like to participate in populating the options menu by receiving a call to onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater) and related methods.
        hasMenu - If true, the fragment has menu items to contribute.
      • setMenuVisibility

        public void setMenuVisibility(boolean menuVisible)
        Set a hint for whether this fragment's menu should be visible. This is useful if you know that a fragment has been placed in your view hierarchy so that the user can not currently seen it, so any menu items it has should also not be shown.
        menuVisible - The default is true, meaning the fragment's menu will be shown as usual. If false, the user will not see the menu.
      • setUserVisibleHint

        public void setUserVisibleHint(boolean isVisibleToUser)
        Set a hint to the system about whether this fragment's UI is currently visible to the user. This hint defaults to true and is persistent across fragment instance state save and restore.

        An app may set this to false to indicate that the fragment's UI is scrolled out of visibility or is otherwise not directly visible to the user. This may be used by the system to prioritize operations such as fragment lifecycle updates or loader ordering behavior.

        isVisibleToUser - true if this fragment's UI is currently visible to the user (default), false if it is not.
      • getUserVisibleHint

        public boolean getUserVisibleHint()
        The current value of the user-visible hint on this fragment.
        See Also:
      • getLoaderManager

        public LoaderManager getLoaderManager()
        Return the LoaderManager for this fragment, creating it if needed.
      • onActivityResult

        public void onActivityResult(int requestCode,
                            int resultCode,
                            Intent data)
        Receive the result from a previous call to startActivityForResult(Intent, int). This follows the related Activity API as described there in Activity.onActivityResult(int, int, Intent).
        requestCode - The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from.
        resultCode - The integer result code returned by the child activity through its setResult().
        data - An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
      • onInflate

        public void onInflate(Activity activity,
                     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. This may be called immediately after the fragment is created from a tag in a layout file. Note this is before the fragment's onAttach(Activity) has been called; all you should do here is parse the attributes and save them away.

        This is called every time the fragment is inflated, even if it is being inflated into a new instance with saved state. It typically makes sense to re-parse the parameters each time, to allow them to change with different configurations.

        Here is a typical implementation of a fragment that can take parameters both through attributes supplied here as well from getArguments():

        Note that parsing the XML attributes uses a "styleable" resource. The declaration for the styleable used here is:

        The fragment can then be declared within its activity's content layout through a tag like this:

        This fragment can also be created dynamically from arguments given at runtime in the arguments Bundle; here is an example of doing so at creation of the containing activity:

        activity - The Activity that is inflating this fragment.
        attrs - The attributes at the tag where the fragment is being created.
        savedInstanceState - If the fragment is being re-created from a previous saved state, this is the state.
      • onAttach

        public void onAttach(Activity activity)
        Called when a fragment is first attached to its activity. onCreate(Bundle) will be called after this.
      • onCreateAnimator

        public Animator onCreateAnimator(int transit,
                                boolean enter,
                                int nextAnim)
        Called when a fragment loads an animation.
      • onCreate

        public void onCreate(Bundle savedInstanceState)
        Called to do initial creation of a fragment. This is called after onAttach(Activity) and before onCreateView(LayoutInflater, ViewGroup, Bundle).

        Note that this can be called while the fragment's activity is still in the process of being created. As such, you can not rely on things like the activity's content view hierarchy being initialized at this point. If you want to do work once the activity itself is created, see onActivityCreated(Bundle).

        savedInstanceState - If the fragment is being re-created from a previous saved state, this is the state.
      • onCreateView

        public View onCreateView(LayoutInflater inflater,
                        ViewGroup container,
                        Bundle savedInstanceState)
        Called to have the fragment instantiate its user interface view. This is optional, and non-graphical fragments can return null (which is the default implementation). This will be called between onCreate(Bundle) and onActivityCreated(Bundle).

        If you return a View from here, you will later be called in onDestroyView() when the view is being released.

        inflater - The LayoutInflater object that can be used to inflate any views in the fragment,
        container - If non-null, this is the parent view that the fragment's UI should be attached to. The fragment should not add the view itself, but this can be used to generate the LayoutParams of the view.
        savedInstanceState - If non-null, this fragment is being re-constructed from a previous saved state as given here.
        Return the View for the fragment's UI, or null.
      • onViewCreated

        public void onViewCreated(View view,
                         Bundle savedInstanceState)
        Called immediately after onCreateView(LayoutInflater, ViewGroup, Bundle) has returned, but before any saved state has been restored in to the view. This gives subclasses a chance to initialize themselves once they know their view hierarchy has been completely created. The fragment's view hierarchy is not however attached to its parent at this point.
        view - The View returned by onCreateView(LayoutInflater, ViewGroup, Bundle).
        savedInstanceState - If non-null, this fragment is being re-constructed from a previous saved state as given here.
      • onActivityCreated

        public void onActivityCreated(Bundle savedInstanceState)
        Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state. It is also useful for fragments that use setRetainInstance(boolean) to retain their instance, as this callback tells the fragment when it is fully associated with the new activity instance. This is called after onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) and before onViewStateRestored(Bundle).
        savedInstanceState - If the fragment is being re-created from a previous saved state, this is the state.
      • onViewStateRestored

        public void onViewStateRestored(Bundle savedInstanceState)
        Called when all saved state has been restored into the view hierarchy of the fragment. This can be used to do initialization based on saved state that you are letting the view hierarchy track itself, such as whether check box widgets are currently checked. This is called after onActivityCreated(Bundle) and before onStart().
        savedInstanceState - If the fragment is being re-created from a previous saved state, this is the state.
      • onStart

        public void onStart()
        Called when the Fragment is visible to the user. This is generally tied to Activity.onStart of the containing Activity's lifecycle.
      • onResume

        public void onResume()
        Called when the fragment is visible to the user and actively running. This is generally tied to Activity.onResume of the containing Activity's lifecycle.
      • onSaveInstanceState

        public 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. If a new instance of the fragment later needs to be created, the data you place in the Bundle here will be available in the Bundle given to onCreate(Bundle), onCreateView(LayoutInflater, ViewGroup, Bundle), and onActivityCreated(Bundle).

        This corresponds to Activity.onSaveInstanceState(Bundle) and most of the discussion there applies here as well. Note however: this method may be called at any time before onDestroy(). There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.

        outState - Bundle in which to place your saved state.
      • onConfigurationChanged

        public void onConfigurationChanged(Configuration newConfig)
        Description copied from interface: ComponentCallbacks
        Called by the system when the device configuration changes while your component is running. Note that, unlike activities, other components are never restarted when a configuration changes: they must always deal with the results of the change, such as by re-retrieving resources.

        At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.

        Specified by:
        onConfigurationChanged in interface ComponentCallbacks
        newConfig - The new device configuration.
      • onPause

        public void onPause()
        Called when the Fragment is no longer resumed. This is generally tied to Activity.onPause of the containing Activity's lifecycle.
      • onStop

        public void onStop()
        Called when the Fragment is no longer started. This is generally tied to Activity.onStop of the containing Activity's lifecycle.
      • onLowMemory

        public void onLowMemory()
        Description copied from interface: ComponentCallbacks
        This is called when the overall system is running low on memory, and would like actively running process to try to tighten their belt. While the exact point at which this will be called is not defined, generally it will happen around the time all background process have been killed, that is before reaching the point of killing processes hosting service and foreground UI that we would like to avoid killing.

        Applications that want to be nice can implement this method to release any caches or other unnecessary resources they may be holding on to. The system will perform a gc for you after returning from this method.

        Specified by:
        onLowMemory in interface ComponentCallbacks
      • onDestroy

        public void onDestroy()
        Called when the fragment is no longer in use. This is called after onStop() and before onDetach().
      • onDetach

        public void onDetach()
        Called when the fragment is no longer attached to its activity. This is called after onDestroy().
      • onDestroyOptionsMenu

        public void onDestroyOptionsMenu()
        Called when this fragment's option menu items are no longer being included in the overall options menu. Receiving this call means that the menu needed to be rebuilt, but this fragment's items were not included in the newly built menu (its onCreateOptionsMenu(Menu, MenuInflater) was not called).
      • onOptionsItemSelected

        public boolean onOptionsItemSelected(MenuItem item)
        This hook is called whenever an item in your options menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.

        Derived classes should call through to the base class for it to perform the default menu handling.

        item - The menu item that was selected.
        boolean Return false to allow normal menu processing to proceed, true to consume it here.
        See Also:
        onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater)
      • onOptionsMenuClosed

        public void onOptionsMenuClosed(Menu menu)
        This hook is called whenever the options menu is being closed (either by the user canceling the menu with the back/menu button, or when an item is selected).
        menu - The options menu as last shown or first initialized by onCreateOptionsMenu().
      • onCreateContextMenu

        public void onCreateContextMenu(ContextMenu menu,
                               View v,
                               ContextMenu.ContextMenuInfo menuInfo)
        Called when a context menu for the view is about to be shown. Unlike onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater), this will be called every time the context menu is about to be shown and should be populated for the view (or item inside the view for AdapterView subclasses, this can be found in the menuInfo)).

        Use onContextItemSelected(android.view.MenuItem) to know when an item has been selected.

        The default implementation calls up to Activity.onCreateContextMenu, though you can not call this implementation if you don't want that behavior.

        It is not safe to hold onto the context menu after this method returns. Called when the context menu for this view is being built. It is not safe to hold onto the menu after this method returns.

        Specified by:
        onCreateContextMenu in interface View.OnCreateContextMenuListener
        menu - The context menu that is being built
        v - The view for which the context menu is being built
        menuInfo - Extra information about the item for which the context menu should be shown. This information will vary depending on the class of v.
      • registerForContextMenu

        public void registerForContextMenu(View view)
        Registers a context menu to be shown for the given view (multiple views can show the context menu). This method will set the View.OnCreateContextMenuListener on the view to this fragment, so #onCreateContextMenu(ContextMenu, View, ContextMenuInfo) will be called when it is time to show the context menu.
        view - The view that should show a context menu.
        See Also:
      • onContextItemSelected

        public boolean onContextItemSelected(MenuItem item)
        This hook is called whenever an item in a context menu is selected. The default implementation simply returns false to have the normal processing happen (calling the item's Runnable or sending a message to its Handler as appropriate). You can use this method for any items for which you would like to do processing without those other facilities.

        Use MenuItem.getMenuInfo() to get extra information set by the View that added this menu item.

        Derived classes should call through to the base class for it to perform the default menu handling.

        item - The context menu item that was selected.
        boolean Return false to allow normal context menu processing to proceed, true to consume it here.
      • dump

        public void dump(String prefix,
                FileDescriptor fd,
                PrintWriter writer,
                String[] args)
        Print the Fragments's state into the given stream.
        prefix - Text to print at the front of each line.
        fd - The raw file descriptor that the dump is being sent to.
        writer - The PrintWriter to which you should dump your state. This will be closed for you after you return.
        args - additional arguments to the dump request.


Android Reference

Java basics

Java Enterprise Edition (EE)

Java Standard Edition (SE)





Java Script








Design patterns

RFC (standard status)

RFC (proposed standard status)

RFC (draft standard status)

RFC (informational status)

RFC (experimental status)

RFC (best current practice status)

RFC (historic status)

RFC (unknown status)

IT dictionary

All information of this service is derived from the free sources and is provided solely in the form of quotations. This service provides information and interfaces solely for the familiarization (not ownership) and under the "as is" condition.
Copyright 2016 © ELTASK.COM. All rights reserved.
Site is optimized for mobile devices.
Downloads: 354 / 159530292. Delta: 0.06767 с