Skip to content

Most visited

Recently visited

navigation
Added in API level 1

PreferenceActivity

public abstract class PreferenceActivity
extends ListActivity implements PreferenceFragment.OnPreferenceStartFragmentCallback

java.lang.Object
   ↳ android.content.Context
     ↳ android.content.ContextWrapper
       ↳ android.view.ContextThemeWrapper
         ↳ android.app.Activity
           ↳ android.app.ListActivity
             ↳ android.preference.PreferenceActivity


This is the base class for an activity to show a hierarchy of preferences to the user. Prior to HONEYCOMB this class only allowed the display of a single set of preference; this functionality should now be found in the new PreferenceFragment class. If you are using PreferenceActivity in its old mode, the documentation there applies to the deprecated APIs here.

This activity shows one or more headers of preferences, each of which is associated with a PreferenceFragment to display the preferences of that header. The actual layout and display of these associations can however vary; currently there are two major approaches it may take:

Subclasses of PreferenceActivity should implement onBuildHeaders(List) to populate the header list with the desired items. Doing this implicitly switches the class into its new "headers + fragments" mode rather than the old style of just showing a single preferences list.

Developer Guides

For information about using PreferenceActivity, read the Settings guide.

Sample Code

The following sample code shows a simple preference activity that has two different sets of preferences. The implementation, consisting of the activity itself as well as its two preference fragments is:

public class PreferenceWithHeaders extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Add a button to the header list.
        if (hasHeaders()) {
            Button button = new Button(this);
            button.setText("Some action");
            setListFooter(button);
        }
    }

    /**
     * Populate the activity with the top-level headers.
     */
    @Override
    public void onBuildHeaders(List<Header> target) {
        loadHeadersFromResource(R.xml.preference_headers, target);
    }

    /**
     * This fragment shows the preferences for the first header.
     */
    public static class Prefs1Fragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Make sure default values are applied.  In a real app, you would
            // want this in a shared function that is used to retrieve the
            // SharedPreferences wherever they are needed.
            PreferenceManager.setDefaultValues(getActivity(),
                    R.xml.advanced_preferences, false);

            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_preferences);
        }
    }

    /**
     * This fragment contains a second-level set of preference that you
     * can get to by tapping an item in the first preferences fragment.
     */
    public static class Prefs1FragmentInner extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Can retrieve arguments from preference XML.
            Log.i("args", "Arguments: " + getArguments());

            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_preferences_inner);
        }
    }

    /**
     * This fragment shows the preferences for the second header.
     */
    public static class Prefs2Fragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Can retrieve arguments from headers XML.
            Log.i("args", "Arguments: " + getArguments());

            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.preference_dependencies);
        }
    }
}

The preference_headers resource describes the headers to be displayed and the fragments associated with them. It is:

<preference-headers
        xmlns:android="http://schemas.android.com/apk/res/android">

    <header android:fragment="com.example.android.apis.preference.PreferenceWithHeaders$Prefs1Fragment"
            android:icon="@drawable/ic_settings_applications"
            android:title="Prefs 1"
            android:summary="An example of some preferences." />

    <header android:fragment="com.example.android.apis.preference.PreferenceWithHeaders$Prefs2Fragment"
            android:icon="@drawable/ic_settings_display"
            android:title="Prefs 2"
            android:summary="Some other preferences you can see.">
        <!-- Arbitrary key/value pairs can be included with a header as
             arguments to its fragment. -->
        <extra android:name="someKey" android:value="someHeaderValue" />
    </header>

    <header android:icon="@drawable/ic_settings_display"
            android:title="Intent"
            android:summary="Launches an Intent.">
        <intent android:action="android.intent.action.VIEW"
                android:data="http://www.android.com" />
    </header>

</preference-headers>

The first header is shown by Prefs1Fragment, which populates itself from the following XML resource:

<PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
            android:title="@string/inline_preferences">

        <CheckBoxPreference
                android:key="checkbox_preference"
                android:title="@string/title_checkbox_preference"
                android:summary="@string/summary_checkbox_preference" />

    </PreferenceCategory>

    <PreferenceCategory
            android:title="@string/dialog_based_preferences">

        <EditTextPreference
                android:key="edittext_preference"
                android:title="@string/title_edittext_preference"
                android:summary="@string/summary_edittext_preference"
                android:dialogTitle="@string/dialog_title_edittext_preference" />

        <ListPreference
                android:key="list_preference"
                android:title="@string/title_list_preference"
                android:summary="@string/summary_list_preference"
                android:entries="@array/entries_list_preference"
                android:entryValues="@array/entryvalues_list_preference"
                android:dialogTitle="@string/dialog_title_list_preference" />

    </PreferenceCategory>

    <PreferenceCategory
            android:title="@string/launch_preferences">

        <!-- This PreferenceScreen tag sends the user to a new fragment of
             preferences.  If running in a large screen, they can be embedded
             inside of the overall preferences UI. -->
        <PreferenceScreen
                android:fragment="com.example.android.apis.preference.PreferenceWithHeaders$Prefs1FragmentInner"
                android:title="@string/title_fragment_preference"
                android:summary="@string/summary_fragment_preference">
            <!-- Arbitrary key/value pairs can be included for fragment arguments -->
            <extra android:name="someKey" android:value="somePrefValue" />
        </PreferenceScreen>

        <!-- This PreferenceScreen tag sends the user to a completely different
             activity, switching out of the current preferences UI. -->
        <PreferenceScreen
                android:title="@string/title_intent_preference"
                android:summary="@string/summary_intent_preference">

            <intent android:action="android.intent.action.VIEW"
                    android:data="http://www.android.com" />

        </PreferenceScreen>

    </PreferenceCategory>

    <PreferenceCategory
            android:title="@string/preference_attributes">

        <CheckBoxPreference
                android:key="parent_checkbox_preference"
                android:title="@string/title_parent_preference"
                android:summary="@string/summary_parent_preference" />

        <!-- The visual style of a child is defined by this styled theme attribute. -->
        <CheckBoxPreference
                android:key="child_checkbox_preference"
                android:dependency="parent_checkbox_preference"
                android:layout="?android:attr/preferenceLayoutChild"
                android:title="@string/title_child_preference"
                android:summary="@string/summary_child_preference" />

    </PreferenceCategory>

</PreferenceScreen>

Note that this XML resource contains a preference screen holding another fragment, the Prefs1FragmentInner implemented here. This allows the user to traverse down a hierarchy of preferences; pressing back will pop each fragment off the stack to return to the previous preferences.

See PreferenceFragment for information on implementing the fragments themselves.

Summary

Nested classes

class PreferenceActivity.Header

Description of a single Header item that the user can select. 

Constants

String EXTRA_NO_HEADERS

When starting this activity, the invoking Intent can contain this extra boolean that the header list should not be displayed.

String EXTRA_SHOW_FRAGMENT

When starting this activity, the invoking Intent can contain this extra string to specify which fragment should be initially displayed.

String EXTRA_SHOW_FRAGMENT_ARGUMENTS

When starting this activity and using EXTRA_SHOW_FRAGMENT, this extra can also be specified to supply a Bundle of arguments to pass to that fragment when it is instantiated during the initial creation of PreferenceActivity.

String EXTRA_SHOW_FRAGMENT_SHORT_TITLE

When starting this activity and using EXTRA_SHOW_FRAGMENT, this extra can also be specify to supply the short title to be shown for that fragment.

String EXTRA_SHOW_FRAGMENT_TITLE

When starting this activity and using EXTRA_SHOW_FRAGMENT, this extra can also be specify to supply the title to be shown for that fragment.

long HEADER_ID_UNDEFINED

Default value for Header.id indicating that no identifier value is set.

Inherited constants

From class android.app.Activity
From class android.content.Context
From interface android.content.ComponentCallbacks2

Inherited fields

From class android.app.Activity

Public constructors

PreferenceActivity()

Public methods

void addPreferencesFromIntent(Intent intent)

This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.

void addPreferencesFromResource(int preferencesResId)

This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.

Preference findPreference(CharSequence key)

This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.

void finishPreferencePanel(Fragment caller, int resultCode, Intent resultData)

Called by a preference panel fragment to finish itself.

PreferenceManager getPreferenceManager()

This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.

PreferenceScreen getPreferenceScreen()

This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.

boolean hasHeaders()

Returns true if this activity is currently showing the header list.

void invalidateHeaders()

Call when you need to change the headers being displayed.

boolean isMultiPane()

Returns true if this activity is showing multiple panes -- the headers and a preference fragment.

void loadHeadersFromResource(int resid, List<PreferenceActivity.Header> target)

Parse the given XML file as a header description, adding each parsed Header into the target list.

void onBuildHeaders(List<PreferenceActivity.Header> target)

Called when the activity needs its list of headers build.

Intent onBuildStartFragmentIntent(String fragmentName, Bundle args, int titleRes, int shortTitleRes)

Called by startWithFragment(String, Bundle, Fragment, int, int, int) when in single-pane mode, to build an Intent to launch a new activity showing the selected fragment.

void onContentChanged()

Updates the screen state (current list and other views) when the content changes.

PreferenceActivity.Header onGetInitialHeader()

Called to determine the initial header to be shown.

PreferenceActivity.Header onGetNewHeader()

Called after the header list has been updated (onBuildHeaders(List) has been called and returned due to invalidateHeaders()) to specify the header that should now be selected.

void onHeaderClick(PreferenceActivity.Header header, int position)

Called when the user selects an item in the header list.

boolean onIsHidingHeaders()

Called to determine whether the header list should be hidden.

boolean onIsMultiPane()

Called to determine if the activity should run in multi-pane mode.

boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref)

Called when the user has clicked on a Preference that has a fragment class name associated with it.

boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference)

This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.

void setListFooter(View view)

Set a footer that should be shown at the bottom of the header list.

void setParentTitle(CharSequence title, CharSequence shortTitle, View.OnClickListener listener)

Should be called after onCreate to ensure that the breadcrumbs, if any, were created.

void setPreferenceScreen(PreferenceScreen preferenceScreen)

This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.

void showBreadCrumbs(CharSequence title, CharSequence shortTitle)

Change the base title of the bread crumbs for the current preferences.

void startPreferenceFragment(Fragment fragment, boolean push)

Start a new fragment.

void startPreferencePanel(String fragmentClass, Bundle args, int titleRes, CharSequence titleText, Fragment resultTo, int resultRequestCode)

Start a new fragment containing a preference panel.

void startWithFragment(String fragmentName, Bundle args, Fragment resultTo, int resultRequestCode)

Like startWithFragment(String, Bundle, Fragment, int, int, int) but uses a 0 titleRes.

void startWithFragment(String fragmentName, Bundle args, Fragment resultTo, int resultRequestCode, int titleRes, int shortTitleRes)

Start a new instance of this activity, showing only the given preference fragment.

void switchToHeader(PreferenceActivity.Header header)

When in two-pane mode, switch to the fragment pane to show the given preference fragment.

void switchToHeader(String fragmentName, Bundle args)

When in two-pane mode, switch the fragment pane to show the given preference fragment.

Protected methods

boolean isValidFragment(String fragmentName)

Subclasses should override this method and verify that the given fragment is a valid type to be attached to this activity.

void onActivityResult(int requestCode, int resultCode, Intent data)

Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it.

void onCreate(Bundle savedInstanceState)

Called when the activity is starting.

void onDestroy()

Perform any final cleanup before an activity is destroyed.

void onListItemClick(ListView l, View v, int position, long id)

This method will be called when an item in the list is selected.

void onNewIntent(Intent intent)

This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent).

void onRestoreInstanceState(Bundle state)

Ensures the list view has been created before Activity restores all of the view states.

void onSaveInstanceState(Bundle outState)

Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

void onStop()

Called when you are no longer visible to the user.

Inherited methods

From class android.app.ListActivity
From class android.app.Activity
From class android.view.ContextThemeWrapper
From class android.content.ContextWrapper
From class android.content.Context
From class java.lang.Object
From interface android.view.LayoutInflater.Factory2
From interface android.view.Window.Callback
From interface android.view.KeyEvent.Callback
From interface android.view.View.OnCreateContextMenuListener
From interface android.content.ComponentCallbacks2
From interface android.preference.PreferenceFragment.OnPreferenceStartFragmentCallback
From interface android.view.LayoutInflater.Factory
From interface android.content.ComponentCallbacks

Constants

EXTRA_NO_HEADERS

Added in API level 11
String EXTRA_NO_HEADERS

When starting this activity, the invoking Intent can contain this extra boolean that the header list should not be displayed. This is most often used in conjunction with EXTRA_SHOW_FRAGMENT to launch the activity to display a specific fragment that the user has navigated to.

Constant Value: ":android:no_headers"

EXTRA_SHOW_FRAGMENT

Added in API level 11
String EXTRA_SHOW_FRAGMENT

When starting this activity, the invoking Intent can contain this extra string to specify which fragment should be initially displayed.

Starting from Key Lime Pie, when this argument is passed in, the PreferenceActivity will call isValidFragment() to confirm that the fragment class name is valid for this activity.

Constant Value: ":android:show_fragment"

EXTRA_SHOW_FRAGMENT_ARGUMENTS

Added in API level 11
String EXTRA_SHOW_FRAGMENT_ARGUMENTS

When starting this activity and using EXTRA_SHOW_FRAGMENT, this extra can also be specified to supply a Bundle of arguments to pass to that fragment when it is instantiated during the initial creation of PreferenceActivity.

Constant Value: ":android:show_fragment_args"

EXTRA_SHOW_FRAGMENT_SHORT_TITLE

Added in API level 14
String EXTRA_SHOW_FRAGMENT_SHORT_TITLE

When starting this activity and using EXTRA_SHOW_FRAGMENT, this extra can also be specify to supply the short title to be shown for that fragment.

Constant Value: ":android:show_fragment_short_title"

EXTRA_SHOW_FRAGMENT_TITLE

Added in API level 14
String EXTRA_SHOW_FRAGMENT_TITLE

When starting this activity and using EXTRA_SHOW_FRAGMENT, this extra can also be specify to supply the title to be shown for that fragment.

Constant Value: ":android:show_fragment_title"

HEADER_ID_UNDEFINED

Added in API level 11
long HEADER_ID_UNDEFINED

Default value for Header.id indicating that no identifier value is set. All other values (including those below -1) are valid.

Constant Value: -1 (0xffffffffffffffff)

Public constructors

PreferenceActivity

Added in API level 1
PreferenceActivity ()

Public methods

addPreferencesFromIntent

Added in API level 1
void addPreferencesFromIntent (Intent intent)

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

Adds preferences from activities that match the given Intent.

Parameters
intent Intent: The Intent to query activities.

addPreferencesFromResource

Added in API level 1
void addPreferencesFromResource (int preferencesResId)

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

Inflates the given XML resource and adds the preference hierarchy to the current preference hierarchy.

Parameters
preferencesResId int: The XML resource ID to inflate.

findPreference

Added in API level 1
Preference findPreference (CharSequence key)

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

Finds a Preference based on its key.

Parameters
key CharSequence: The key of the preference to retrieve.
Returns
Preference The Preference with the key, or null.

See also:

finishPreferencePanel

Added in API level 11
void finishPreferencePanel (Fragment caller, 
                int resultCode, 
                Intent resultData)

Called by a preference panel fragment to finish itself.

Parameters
caller Fragment: The fragment that is asking to be finished.
resultCode int: Optional result code to send back to the original launching fragment.
resultData Intent: Optional result data to send back to the original launching fragment.

getPreferenceManager

Added in API level 1
PreferenceManager getPreferenceManager ()

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

Returns the PreferenceManager used by this activity.

Returns
PreferenceManager The PreferenceManager.

getPreferenceScreen

Added in API level 1
PreferenceScreen getPreferenceScreen ()

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

Gets the root of the preference hierarchy that this activity is showing.

Returns
PreferenceScreen The PreferenceScreen that is the root of the preference hierarchy.

hasHeaders

Added in API level 11
boolean hasHeaders ()

Returns true if this activity is currently showing the header list.

Returns
boolean

invalidateHeaders

Added in API level 11
void invalidateHeaders ()

Call when you need to change the headers being displayed. Will result in onBuildHeaders() later being called to retrieve the new list.

isMultiPane

Added in API level 11
boolean isMultiPane ()

Returns true if this activity is showing multiple panes -- the headers and a preference fragment.

Returns
boolean

loadHeadersFromResource

Added in API level 11
void loadHeadersFromResource (int resid, 
                List<PreferenceActivity.Header> target)

Parse the given XML file as a header description, adding each parsed Header into the target list.

Parameters
resid int: The XML resource to load and parse.
target List: The list in which the parsed headers should be placed.

onBuildHeaders

Added in API level 11
void onBuildHeaders (List<PreferenceActivity.Header> target)

Called when the activity needs its list of headers build. By implementing this and adding at least one item to the list, you will cause the activity to run in its modern fragment mode. Note that this function may not always be called; for example, if the activity has been asked to display a particular fragment without the header list, there is no need to build the headers.

Typical implementations will use loadHeadersFromResource(int, List) to fill in the list from a resource.

Parameters
target List: The list in which to place the headers.

onBuildStartFragmentIntent

Added in API level 14
Intent onBuildStartFragmentIntent (String fragmentName, 
                Bundle args, 
                int titleRes, 
                int shortTitleRes)

Called by startWithFragment(String, Bundle, Fragment, int, int, int) when in single-pane mode, to build an Intent to launch a new activity showing the selected fragment. The default implementation constructs an Intent that re-launches the current activity with the appropriate arguments to display the fragment.

Parameters
fragmentName String: The name of the fragment to display.
args Bundle: Optional arguments to supply to the fragment.
titleRes int: Optional resource ID of title to show for this item.
shortTitleRes int: Optional resource ID of short title to show for this item.
Returns
Intent Returns an Intent that can be launched to display the given fragment.

onContentChanged

Added in API level 1
void onContentChanged ()

Updates the screen state (current list and other views) when the content changes.

onGetInitialHeader

Added in API level 11
PreferenceActivity.Header onGetInitialHeader ()

Called to determine the initial header to be shown. The default implementation simply returns the fragment of the first header. Note that the returned Header object does not actually need to exist in your header list -- whatever its fragment is will simply be used to show for the initial UI.

Returns
PreferenceActivity.Header

onGetNewHeader

Added in API level 11
PreferenceActivity.Header onGetNewHeader ()

Called after the header list has been updated (onBuildHeaders(List) has been called and returned due to invalidateHeaders()) to specify the header that should now be selected. The default implementation returns null to keep whatever header is currently selected.

Returns
PreferenceActivity.Header

onHeaderClick

Added in API level 11
void onHeaderClick (PreferenceActivity.Header header, 
                int position)

Called when the user selects an item in the header list. The default implementation will call either startWithFragment(String, Bundle, Fragment, int, int, int) or switchToHeader(Header) as appropriate.

Parameters
header PreferenceActivity.Header: The header that was selected.
position int: The header's position in the list.

onIsHidingHeaders

Added in API level 11
boolean onIsHidingHeaders ()

Called to determine whether the header list should be hidden. The default implementation returns the value given in EXTRA_NO_HEADERS or false if it is not supplied. This is set to false, for example, when the activity is being re-launched to show a particular preference activity.

Returns
boolean

onIsMultiPane

Added in API level 11
boolean onIsMultiPane ()

Called to determine if the activity should run in multi-pane mode. The default implementation returns true if the screen is large enough.

Returns
boolean

onPreferenceStartFragment

Added in API level 11
boolean onPreferenceStartFragment (PreferenceFragment caller, 
                Preference pref)

Called when the user has clicked on a Preference that has a fragment class name associated with it. The implementation to should instantiate and switch to an instance of the given fragment.

Parameters
caller PreferenceFragment
pref Preference
Returns
boolean

onPreferenceTreeClick

Added in API level 1
boolean onPreferenceTreeClick (PreferenceScreen preferenceScreen, 
                Preference preference)

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

Parameters
preferenceScreen PreferenceScreen
preference Preference
Returns
boolean

setListFooter

Added in API level 11
void setListFooter (View view)

Set a footer that should be shown at the bottom of the header list.

Parameters
view View

setParentTitle

Added in API level 11
void setParentTitle (CharSequence title, 
                CharSequence shortTitle, 
                View.OnClickListener listener)

Should be called after onCreate to ensure that the breadcrumbs, if any, were created. This prepends a title to the fragment breadcrumbs and attaches a listener to any clicks on the parent entry.

Parameters
title CharSequence: the title for the breadcrumb
shortTitle CharSequence: the short title for the breadcrumb
listener View.OnClickListener

setPreferenceScreen

Added in API level 1
void setPreferenceScreen (PreferenceScreen preferenceScreen)

This method was deprecated in API level 11.
This function is not relevant for a modern fragment-based PreferenceActivity.

Sets the root of the preference hierarchy that this activity is showing.

Parameters
preferenceScreen PreferenceScreen: The root PreferenceScreen of the preference hierarchy.

showBreadCrumbs

Added in API level 11
void showBreadCrumbs (CharSequence title, 
                CharSequence shortTitle)

Change the base title of the bread crumbs for the current preferences. This will normally be called for you. See FragmentBreadCrumbs for more information.

Parameters
title CharSequence
shortTitle CharSequence

startPreferenceFragment

Added in API level 11
void startPreferenceFragment (Fragment fragment, 
                boolean push)

Start a new fragment.

Parameters
fragment Fragment: The fragment to start
push boolean: If true, the current fragment will be pushed onto the back stack. If false, the current fragment will be replaced.

startPreferencePanel

Added in API level 11
void startPreferencePanel (String fragmentClass, 
                Bundle args, 
                int titleRes, 
                CharSequence titleText, 
                Fragment resultTo, 
                int resultRequestCode)

Start a new fragment containing a preference panel. If the preferences are being displayed in multi-pane mode, the given fragment class will be instantiated and placed in the appropriate pane. If running in single-pane mode, a new activity will be launched in which to show the fragment.

Parameters
fragmentClass String: Full name of the class implementing the fragment.
args Bundle: Any desired arguments to supply to the fragment.
titleRes int: Optional resource identifier of the title of this fragment.
titleText CharSequence: Optional text of the title of this fragment.
resultTo Fragment: Optional fragment that result data should be sent to. If non-null, resultTo.onActivityResult() will be called when this preference panel is done. The launched panel must use finishPreferencePanel(Fragment, int, Intent) when done.
resultRequestCode int: If resultTo is non-null, this is the caller's request code to be received with the result.

startWithFragment

Added in API level 11
void startWithFragment (String fragmentName, 
                Bundle args, 
                Fragment resultTo, 
                int resultRequestCode)

Like startWithFragment(String, Bundle, Fragment, int, int, int) but uses a 0 titleRes.

Parameters
fragmentName String
args Bundle
resultTo Fragment
resultRequestCode int

startWithFragment

Added in API level 14
void startWithFragment (String fragmentName, 
                Bundle args, 
                Fragment resultTo, 
                int resultRequestCode, 
                int titleRes, 
                int shortTitleRes)

Start a new instance of this activity, showing only the given preference fragment. When launched in this mode, the header list will be hidden and the given preference fragment will be instantiated and fill the entire activity.

Parameters
fragmentName String: The name of the fragment to display.
args Bundle: Optional arguments to supply to the fragment.
resultTo Fragment: Option fragment that should receive the result of the activity launch.
resultRequestCode int: If resultTo is non-null, this is the request code in which to report the result.
titleRes int: Resource ID of string to display for the title of this set of preferences.
shortTitleRes int: Resource ID of string to display for the short title of this set of preferences.

switchToHeader

Added in API level 11
void switchToHeader (PreferenceActivity.Header header)

When in two-pane mode, switch to the fragment pane to show the given preference fragment.

Parameters
header PreferenceActivity.Header: The new header to display.

switchToHeader

Added in API level 11
void switchToHeader (String fragmentName, 
                Bundle args)

When in two-pane mode, switch the fragment pane to show the given preference fragment.

Parameters
fragmentName String: The name of the fragment to display.
args Bundle: Optional arguments to supply to the fragment.

Protected methods

isValidFragment

Added in API level 19
boolean isValidFragment (String fragmentName)

Subclasses should override this method and verify that the given fragment is a valid type to be attached to this activity. The default implementation returns true for apps built for android:targetSdkVersion older than KITKAT. For later versions, it will throw an exception.

Parameters
fragmentName String: the class name of the Fragment about to be attached to this activity.
Returns
boolean true if the fragment class name is valid for this Activity and false otherwise.

onActivityResult

Added in API level 1
void onActivityResult (int requestCode, 
                int resultCode, 
                Intent data)

Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it. The resultCode will be RESULT_CANCELED if the activity explicitly returned that, didn't return any result, or crashed during its operation.

You will receive this call immediately before onResume() when your activity is re-starting.

This method is never invoked if your activity sets noHistory to true.

Parameters
requestCode int: The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from.
resultCode int: The integer result code returned by the child activity through its setResult().
data Intent: An Intent, which can return result data to the caller (various data can be attached to Intent "extras").

onCreate

Added in API level 1
void onCreate (Bundle savedInstanceState)

Called when the activity is starting. This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById(int) to programmatically interact with widgets in the UI, calling managedQuery(android.net.Uri, String[], String, String[], String) to retrieve cursors for data being displayed, etc.

You can call finish() from within this function, in which case onDestroy() will be immediately called without any of the rest of the activity lifecycle (onStart(), onResume(), onPause(), etc) executing.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

Parameters
savedInstanceState Bundle: If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle). Note: Otherwise it is null.

onDestroy

Added in API level 1
void onDestroy ()

Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

onListItemClick

Added in API level 1
void onListItemClick (ListView l, 
                View v, 
                int position, 
                long id)

This method will be called when an item in the list is selected. Subclasses should override. Subclasses can call getListView().getItemAtPosition(position) if they need to access the data associated with the selected item.

Parameters
l ListView: The ListView where the click happened
v View: The view that was clicked within the ListView
position int: The position of the view in the list
id long: The row id of the item that was clicked

onNewIntent

Added in API level 1
void onNewIntent (Intent intent)

This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent). In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.

An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method.

Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.

Parameters
intent Intent: The new intent that was started for the activity.

onRestoreInstanceState

Added in API level 1
void onRestoreInstanceState (Bundle state)

Ensures the list view has been created before Activity restores all of the view states.

Parameters
state Bundle: the data most recently supplied in onSaveInstanceState(Bundle).

onSaveInstanceState

Added in API level 1
void onSaveInstanceState (Bundle outState)

Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via onCreate(Bundle) or onRestoreInstanceState(Bundle).

Do not confuse this method with activity lifecycle callbacks such as onPause(), which is always called when an activity is being placed in the background or on its way to destruction, or onStop() which is called before destruction. One example of when onPause() and onStop() is called and not this method is when a user navigates back from activity B to activity A: there is no need to call onSaveInstanceState(Bundle) on B because that particular instance will never be restored, so the system avoids calling it. An example when onPause() is called and not onSaveInstanceState(Bundle) is when activity B is launched in front of activity A: the system may avoid calling onSaveInstanceState(Bundle) on activity A if it isn't killed during the lifetime of B since the state of the user interface of A will stay intact.

The default implementation takes care of most of the UI per-instance state for you by calling onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState(Bundle)). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation, otherwise be prepared to save all of the state of each view yourself.

If called, this method will occur before onStop(). There are no guarantees about whether it will occur before or after onPause().

Parameters
outState Bundle: Bundle in which to place your saved state.

onStop

Added in API level 1
void onStop ()

Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

This site uses cookies to store your preferences for site-specific language and display options.

Hooray!

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.