PreferenceActivity.java revision 7db97b0a29c613afb78c2734bf2504324a71963d
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.preference;
18
19import android.app.Fragment;
20import android.app.FragmentBreadCrumbs;
21import android.app.FragmentManager;
22import android.app.FragmentTransaction;
23import android.app.ListActivity;
24import android.content.Context;
25import android.content.Intent;
26import android.content.res.Resources;
27import android.content.res.TypedArray;
28import android.content.res.XmlResourceParser;
29import android.os.Bundle;
30import android.os.Handler;
31import android.os.Message;
32import android.os.Parcel;
33import android.os.Parcelable;
34import android.text.TextUtils;
35import android.util.AttributeSet;
36import android.util.TypedValue;
37import android.util.Xml;
38import android.view.LayoutInflater;
39import android.view.View;
40import android.view.View.OnClickListener;
41import android.view.ViewGroup;
42import android.widget.AbsListView;
43import android.widget.ArrayAdapter;
44import android.widget.BaseAdapter;
45import android.widget.Button;
46import android.widget.FrameLayout;
47import android.widget.ImageView;
48import android.widget.ListView;
49import android.widget.TextView;
50
51import com.android.internal.util.XmlUtils;
52
53import org.xmlpull.v1.XmlPullParser;
54import org.xmlpull.v1.XmlPullParserException;
55
56import java.io.IOException;
57import java.util.ArrayList;
58import java.util.List;
59
60/**
61 * This is the base class for an activity to show a hierarchy of preferences
62 * to the user.  Prior to {@link android.os.Build.VERSION_CODES#HONEYCOMB}
63 * this class only allowed the display of a single set of preference; this
64 * functionality should now be found in the new {@link PreferenceFragment}
65 * class.  If you are using PreferenceActivity in its old mode, the documentation
66 * there applies to the deprecated APIs here.
67 *
68 * <p>This activity shows one or more headers of preferences, each of which
69 * is associated with a {@link PreferenceFragment} to display the preferences
70 * of that header.  The actual layout and display of these associations can
71 * however vary; currently there are two major approaches it may take:
72 *
73 * <ul>
74 * <li>On a small screen it may display only the headers as a single list
75 * when first launched.  Selecting one of the header items will re-launch
76 * the activity with it only showing the PreferenceFragment of that header.
77 * <li>On a large screen in may display both the headers and current
78 * PreferenceFragment together as panes.  Selecting a header item switches
79 * to showing the correct PreferenceFragment for that item.
80 * </ul>
81 *
82 * <p>Subclasses of PreferenceActivity should implement
83 * {@link #onBuildHeaders} to populate the header list with the desired
84 * items.  Doing this implicitly switches the class into its new "headers
85 * + fragments" mode rather than the old style of just showing a single
86 * preferences list.
87 *
88 * <div class="special reference">
89 * <h3>Developer Guides</h3>
90 * <p>For information about using {@code PreferenceActivity},
91 * read the <a href="{@docRoot}guide/topics/ui/settings.html">Settings</a>
92 * guide.</p>
93 * </div>
94 *
95 * <a name="SampleCode"></a>
96 * <h3>Sample Code</h3>
97 *
98 * <p>The following sample code shows a simple preference activity that
99 * has two different sets of preferences.  The implementation, consisting
100 * of the activity itself as well as its two preference fragments is:</p>
101 *
102 * {@sample development/samples/ApiDemos/src/com/example/android/apis/preference/PreferenceWithHeaders.java
103 *      activity}
104 *
105 * <p>The preference_headers resource describes the headers to be displayed
106 * and the fragments associated with them.  It is:
107 *
108 * {@sample development/samples/ApiDemos/res/xml/preference_headers.xml headers}
109 *
110 * <p>The first header is shown by Prefs1Fragment, which populates itself
111 * from the following XML resource:</p>
112 *
113 * {@sample development/samples/ApiDemos/res/xml/fragmented_preferences.xml preferences}
114 *
115 * <p>Note that this XML resource contains a preference screen holding another
116 * fragment, the Prefs1FragmentInner implemented here.  This allows the user
117 * to traverse down a hierarchy of preferences; pressing back will pop each
118 * fragment off the stack to return to the previous preferences.
119 *
120 * <p>See {@link PreferenceFragment} for information on implementing the
121 * fragments themselves.
122 */
123public abstract class PreferenceActivity extends ListActivity implements
124        PreferenceManager.OnPreferenceTreeClickListener,
125        PreferenceFragment.OnPreferenceStartFragmentCallback {
126
127    // Constants for state save/restore
128    private static final String HEADERS_TAG = ":android:headers";
129    private static final String CUR_HEADER_TAG = ":android:cur_header";
130    private static final String PREFERENCES_TAG = ":android:preferences";
131
132    /**
133     * When starting this activity, the invoking Intent can contain this extra
134     * string to specify which fragment should be initially displayed.
135     * <p/>Starting from Key Lime Pie, when this argument is passed in, the PreferenceActivity
136     * will call isValidFragment() to confirm that the fragment class name is valid for this
137     * activity.
138     */
139    public static final String EXTRA_SHOW_FRAGMENT = ":android:show_fragment";
140
141    /**
142     * When starting this activity and using {@link #EXTRA_SHOW_FRAGMENT},
143     * this extra can also be specified to supply a Bundle of arguments to pass
144     * to that fragment when it is instantiated during the initial creation
145     * of PreferenceActivity.
146     */
147    public static final String EXTRA_SHOW_FRAGMENT_ARGUMENTS = ":android:show_fragment_args";
148
149    /**
150     * When starting this activity and using {@link #EXTRA_SHOW_FRAGMENT},
151     * this extra can also be specify to supply the title to be shown for
152     * that fragment.
153     */
154    public static final String EXTRA_SHOW_FRAGMENT_TITLE = ":android:show_fragment_title";
155
156    /**
157     * When starting this activity and using {@link #EXTRA_SHOW_FRAGMENT},
158     * this extra can also be specify to supply the short title to be shown for
159     * that fragment.
160     */
161    public static final String EXTRA_SHOW_FRAGMENT_SHORT_TITLE
162            = ":android:show_fragment_short_title";
163
164    /**
165     * When starting this activity, the invoking Intent can contain this extra
166     * boolean that the header list should not be displayed.  This is most often
167     * used in conjunction with {@link #EXTRA_SHOW_FRAGMENT} to launch
168     * the activity to display a specific fragment that the user has navigated
169     * to.
170     */
171    public static final String EXTRA_NO_HEADERS = ":android:no_headers";
172
173    private static final String BACK_STACK_PREFS = ":android:prefs";
174
175    // extras that allow any preference activity to be launched as part of a wizard
176
177    // show Back and Next buttons? takes boolean parameter
178    // Back will then return RESULT_CANCELED and Next RESULT_OK
179    private static final String EXTRA_PREFS_SHOW_BUTTON_BAR = "extra_prefs_show_button_bar";
180
181    // add a Skip button?
182    private static final String EXTRA_PREFS_SHOW_SKIP = "extra_prefs_show_skip";
183
184    // specify custom text for the Back or Next buttons, or cause a button to not appear
185    // at all by setting it to null
186    private static final String EXTRA_PREFS_SET_NEXT_TEXT = "extra_prefs_set_next_text";
187    private static final String EXTRA_PREFS_SET_BACK_TEXT = "extra_prefs_set_back_text";
188
189    // --- State for new mode when showing a list of headers + prefs fragment
190
191    private final ArrayList<Header> mHeaders = new ArrayList<Header>();
192
193    private FrameLayout mListFooter;
194
195    private ViewGroup mPrefsContainer;
196
197    private FragmentBreadCrumbs mFragmentBreadCrumbs;
198
199    private boolean mSinglePane;
200
201    private Header mCurHeader;
202
203    // --- State for old mode when showing a single preference list
204
205    private PreferenceManager mPreferenceManager;
206
207    private Bundle mSavedInstanceState;
208
209    // --- Common state
210
211    private Button mNextButton;
212
213    /**
214     * The starting request code given out to preference framework.
215     */
216    private static final int FIRST_REQUEST_CODE = 100;
217
218    private static final int MSG_BIND_PREFERENCES = 1;
219    private static final int MSG_BUILD_HEADERS = 2;
220    private Handler mHandler = new Handler() {
221        @Override
222        public void handleMessage(Message msg) {
223            switch (msg.what) {
224                case MSG_BIND_PREFERENCES: {
225                    bindPreferences();
226                } break;
227                case MSG_BUILD_HEADERS: {
228                    ArrayList<Header> oldHeaders = new ArrayList<Header>(mHeaders);
229                    mHeaders.clear();
230                    onBuildHeaders(mHeaders);
231                    if (mAdapter instanceof BaseAdapter) {
232                        ((BaseAdapter) mAdapter).notifyDataSetChanged();
233                    }
234                    Header header = onGetNewHeader();
235                    if (header != null && header.fragment != null) {
236                        Header mappedHeader = findBestMatchingHeader(header, oldHeaders);
237                        if (mappedHeader == null || mCurHeader != mappedHeader) {
238                            switchToHeader(header);
239                        }
240                    } else if (mCurHeader != null) {
241                        Header mappedHeader = findBestMatchingHeader(mCurHeader, mHeaders);
242                        if (mappedHeader != null) {
243                            setSelectedHeader(mappedHeader);
244                        }
245                    }
246                } break;
247            }
248        }
249    };
250
251    private static class HeaderAdapter extends ArrayAdapter<Header> {
252        private static class HeaderViewHolder {
253            ImageView icon;
254            TextView title;
255            TextView summary;
256        }
257
258        private LayoutInflater mInflater;
259
260        public HeaderAdapter(Context context, List<Header> objects) {
261            super(context, 0, objects);
262            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
263        }
264
265        @Override
266        public View getView(int position, View convertView, ViewGroup parent) {
267            HeaderViewHolder holder;
268            View view;
269
270            if (convertView == null) {
271                view = mInflater.inflate(com.android.internal.R.layout.preference_header_item,
272                        parent, false);
273                holder = new HeaderViewHolder();
274                holder.icon = (ImageView) view.findViewById(com.android.internal.R.id.icon);
275                holder.title = (TextView) view.findViewById(com.android.internal.R.id.title);
276                holder.summary = (TextView) view.findViewById(com.android.internal.R.id.summary);
277                view.setTag(holder);
278            } else {
279                view = convertView;
280                holder = (HeaderViewHolder) view.getTag();
281            }
282
283            // All view fields must be updated every time, because the view may be recycled
284            Header header = getItem(position);
285            holder.icon.setImageResource(header.iconRes);
286            holder.title.setText(header.getTitle(getContext().getResources()));
287            CharSequence summary = header.getSummary(getContext().getResources());
288            if (!TextUtils.isEmpty(summary)) {
289                holder.summary.setVisibility(View.VISIBLE);
290                holder.summary.setText(summary);
291            } else {
292                holder.summary.setVisibility(View.GONE);
293            }
294
295            return view;
296        }
297    }
298
299    /**
300     * Default value for {@link Header#id Header.id} indicating that no
301     * identifier value is set.  All other values (including those below -1)
302     * are valid.
303     */
304    public static final long HEADER_ID_UNDEFINED = -1;
305
306    /**
307     * Description of a single Header item that the user can select.
308     */
309    public static final class Header implements Parcelable {
310        /**
311         * Identifier for this header, to correlate with a new list when
312         * it is updated.  The default value is
313         * {@link PreferenceActivity#HEADER_ID_UNDEFINED}, meaning no id.
314         * @attr ref android.R.styleable#PreferenceHeader_id
315         */
316        public long id = HEADER_ID_UNDEFINED;
317
318        /**
319         * Resource ID of title of the header that is shown to the user.
320         * @attr ref android.R.styleable#PreferenceHeader_title
321         */
322        public int titleRes;
323
324        /**
325         * Title of the header that is shown to the user.
326         * @attr ref android.R.styleable#PreferenceHeader_title
327         */
328        public CharSequence title;
329
330        /**
331         * Resource ID of optional summary describing what this header controls.
332         * @attr ref android.R.styleable#PreferenceHeader_summary
333         */
334        public int summaryRes;
335
336        /**
337         * Optional summary describing what this header controls.
338         * @attr ref android.R.styleable#PreferenceHeader_summary
339         */
340        public CharSequence summary;
341
342        /**
343         * Resource ID of optional text to show as the title in the bread crumb.
344         * @attr ref android.R.styleable#PreferenceHeader_breadCrumbTitle
345         */
346        public int breadCrumbTitleRes;
347
348        /**
349         * Optional text to show as the title in the bread crumb.
350         * @attr ref android.R.styleable#PreferenceHeader_breadCrumbTitle
351         */
352        public CharSequence breadCrumbTitle;
353
354        /**
355         * Resource ID of optional text to show as the short title in the bread crumb.
356         * @attr ref android.R.styleable#PreferenceHeader_breadCrumbShortTitle
357         */
358        public int breadCrumbShortTitleRes;
359
360        /**
361         * Optional text to show as the short title in the bread crumb.
362         * @attr ref android.R.styleable#PreferenceHeader_breadCrumbShortTitle
363         */
364        public CharSequence breadCrumbShortTitle;
365
366        /**
367         * Optional icon resource to show for this header.
368         * @attr ref android.R.styleable#PreferenceHeader_icon
369         */
370        public int iconRes;
371
372        /**
373         * Full class name of the fragment to display when this header is
374         * selected.
375         * @attr ref android.R.styleable#PreferenceHeader_fragment
376         */
377        public String fragment;
378
379        /**
380         * Optional arguments to supply to the fragment when it is
381         * instantiated.
382         */
383        public Bundle fragmentArguments;
384
385        /**
386         * Intent to launch when the preference is selected.
387         */
388        public Intent intent;
389
390        /**
391         * Optional additional data for use by subclasses of PreferenceActivity.
392         */
393        public Bundle extras;
394
395        public Header() {
396            // Empty
397        }
398
399        /**
400         * Return the currently set title.  If {@link #titleRes} is set,
401         * this resource is loaded from <var>res</var> and returned.  Otherwise
402         * {@link #title} is returned.
403         */
404        public CharSequence getTitle(Resources res) {
405            if (titleRes != 0) {
406                return res.getText(titleRes);
407            }
408            return title;
409        }
410
411        /**
412         * Return the currently set summary.  If {@link #summaryRes} is set,
413         * this resource is loaded from <var>res</var> and returned.  Otherwise
414         * {@link #summary} is returned.
415         */
416        public CharSequence getSummary(Resources res) {
417            if (summaryRes != 0) {
418                return res.getText(summaryRes);
419            }
420            return summary;
421        }
422
423        /**
424         * Return the currently set bread crumb title.  If {@link #breadCrumbTitleRes} is set,
425         * this resource is loaded from <var>res</var> and returned.  Otherwise
426         * {@link #breadCrumbTitle} is returned.
427         */
428        public CharSequence getBreadCrumbTitle(Resources res) {
429            if (breadCrumbTitleRes != 0) {
430                return res.getText(breadCrumbTitleRes);
431            }
432            return breadCrumbTitle;
433        }
434
435        /**
436         * Return the currently set bread crumb short title.  If
437         * {@link #breadCrumbShortTitleRes} is set,
438         * this resource is loaded from <var>res</var> and returned.  Otherwise
439         * {@link #breadCrumbShortTitle} is returned.
440         */
441        public CharSequence getBreadCrumbShortTitle(Resources res) {
442            if (breadCrumbShortTitleRes != 0) {
443                return res.getText(breadCrumbShortTitleRes);
444            }
445            return breadCrumbShortTitle;
446        }
447
448        @Override
449        public int describeContents() {
450            return 0;
451        }
452
453        @Override
454        public void writeToParcel(Parcel dest, int flags) {
455            dest.writeLong(id);
456            dest.writeInt(titleRes);
457            TextUtils.writeToParcel(title, dest, flags);
458            dest.writeInt(summaryRes);
459            TextUtils.writeToParcel(summary, dest, flags);
460            dest.writeInt(breadCrumbTitleRes);
461            TextUtils.writeToParcel(breadCrumbTitle, dest, flags);
462            dest.writeInt(breadCrumbShortTitleRes);
463            TextUtils.writeToParcel(breadCrumbShortTitle, dest, flags);
464            dest.writeInt(iconRes);
465            dest.writeString(fragment);
466            dest.writeBundle(fragmentArguments);
467            if (intent != null) {
468                dest.writeInt(1);
469                intent.writeToParcel(dest, flags);
470            } else {
471                dest.writeInt(0);
472            }
473            dest.writeBundle(extras);
474        }
475
476        public void readFromParcel(Parcel in) {
477            id = in.readLong();
478            titleRes = in.readInt();
479            title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
480            summaryRes = in.readInt();
481            summary = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
482            breadCrumbTitleRes = in.readInt();
483            breadCrumbTitle = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
484            breadCrumbShortTitleRes = in.readInt();
485            breadCrumbShortTitle = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
486            iconRes = in.readInt();
487            fragment = in.readString();
488            fragmentArguments = in.readBundle();
489            if (in.readInt() != 0) {
490                intent = Intent.CREATOR.createFromParcel(in);
491            }
492            extras = in.readBundle();
493        }
494
495        Header(Parcel in) {
496            readFromParcel(in);
497        }
498
499        public static final Creator<Header> CREATOR = new Creator<Header>() {
500            public Header createFromParcel(Parcel source) {
501                return new Header(source);
502            }
503            public Header[] newArray(int size) {
504                return new Header[size];
505            }
506        };
507    }
508
509    @Override
510    protected void onCreate(Bundle savedInstanceState) {
511        super.onCreate(savedInstanceState);
512
513        setContentView(com.android.internal.R.layout.preference_list_content);
514
515        mListFooter = (FrameLayout)findViewById(com.android.internal.R.id.list_footer);
516        mPrefsContainer = (ViewGroup) findViewById(com.android.internal.R.id.prefs_frame);
517        boolean hidingHeaders = onIsHidingHeaders();
518        mSinglePane = hidingHeaders || !onIsMultiPane();
519        String initialFragment = getIntent().getStringExtra(EXTRA_SHOW_FRAGMENT);
520        Bundle initialArguments = getIntent().getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS);
521        int initialTitle = getIntent().getIntExtra(EXTRA_SHOW_FRAGMENT_TITLE, 0);
522        int initialShortTitle = getIntent().getIntExtra(EXTRA_SHOW_FRAGMENT_SHORT_TITLE, 0);
523
524        if (savedInstanceState != null) {
525            // We are restarting from a previous saved state; used that to
526            // initialize, instead of starting fresh.
527            ArrayList<Header> headers = savedInstanceState.getParcelableArrayList(HEADERS_TAG);
528            if (headers != null) {
529                mHeaders.addAll(headers);
530                int curHeader = savedInstanceState.getInt(CUR_HEADER_TAG,
531                        (int) HEADER_ID_UNDEFINED);
532                if (curHeader >= 0 && curHeader < mHeaders.size()) {
533                    setSelectedHeader(mHeaders.get(curHeader));
534                }
535            }
536
537        } else {
538            if (initialFragment != null && mSinglePane) {
539                // If we are just showing a fragment, we want to run in
540                // new fragment mode, but don't need to compute and show
541                // the headers.
542                switchToHeader(initialFragment, initialArguments);
543                if (initialTitle != 0) {
544                    CharSequence initialTitleStr = getText(initialTitle);
545                    CharSequence initialShortTitleStr = initialShortTitle != 0
546                            ? getText(initialShortTitle) : null;
547                    showBreadCrumbs(initialTitleStr, initialShortTitleStr);
548                }
549
550            } else {
551                // We need to try to build the headers.
552                onBuildHeaders(mHeaders);
553
554                // If there are headers, then at this point we need to show
555                // them and, depending on the screen, we may also show in-line
556                // the currently selected preference fragment.
557                if (mHeaders.size() > 0) {
558                    if (!mSinglePane) {
559                        if (initialFragment == null) {
560                            Header h = onGetInitialHeader();
561                            switchToHeader(h);
562                        } else {
563                            switchToHeader(initialFragment, initialArguments);
564                        }
565                    }
566                }
567            }
568        }
569
570        // The default configuration is to only show the list view.  Adjust
571        // visibility for other configurations.
572        if (initialFragment != null && mSinglePane) {
573            // Single pane, showing just a prefs fragment.
574            findViewById(com.android.internal.R.id.headers).setVisibility(View.GONE);
575            mPrefsContainer.setVisibility(View.VISIBLE);
576            CharSequence initialTitleStr = null;
577            CharSequence initialShortTitleStr = null;
578            if (initialTitle != 0) {
579                initialTitleStr = getText(initialTitle);
580                initialShortTitleStr = initialShortTitle != 0
581                        ? getText(initialShortTitle) : null;
582            }
583            showBreadCrumbs(initialTitleStr, initialShortTitleStr);
584        } else if (mHeaders.size() > 0) {
585            setListAdapter(new HeaderAdapter(this, mHeaders));
586            if (!mSinglePane) {
587                // Multi-pane.
588                getListView().setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
589                if (mCurHeader != null) {
590                    setSelectedHeader(mCurHeader);
591                }
592                mPrefsContainer.setVisibility(View.VISIBLE);
593            }
594        } else {
595            // If there are no headers, we are in the old "just show a screen
596            // of preferences" mode.
597            setContentView(com.android.internal.R.layout.preference_list_content_single);
598            mListFooter = (FrameLayout) findViewById(com.android.internal.R.id.list_footer);
599            mPrefsContainer = (ViewGroup) findViewById(com.android.internal.R.id.prefs);
600            mPreferenceManager = new PreferenceManager(this, FIRST_REQUEST_CODE);
601            mPreferenceManager.setOnPreferenceTreeClickListener(this);
602        }
603
604        // see if we should show Back/Next buttons
605        Intent intent = getIntent();
606        if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_BUTTON_BAR, false)) {
607
608            findViewById(com.android.internal.R.id.button_bar).setVisibility(View.VISIBLE);
609
610            Button backButton = (Button)findViewById(com.android.internal.R.id.back_button);
611            backButton.setOnClickListener(new OnClickListener() {
612                public void onClick(View v) {
613                    setResult(RESULT_CANCELED);
614                    finish();
615                }
616            });
617            Button skipButton = (Button)findViewById(com.android.internal.R.id.skip_button);
618            skipButton.setOnClickListener(new OnClickListener() {
619                public void onClick(View v) {
620                    setResult(RESULT_OK);
621                    finish();
622                }
623            });
624            mNextButton = (Button)findViewById(com.android.internal.R.id.next_button);
625            mNextButton.setOnClickListener(new OnClickListener() {
626                public void onClick(View v) {
627                    setResult(RESULT_OK);
628                    finish();
629                }
630            });
631
632            // set our various button parameters
633            if (intent.hasExtra(EXTRA_PREFS_SET_NEXT_TEXT)) {
634                String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_NEXT_TEXT);
635                if (TextUtils.isEmpty(buttonText)) {
636                    mNextButton.setVisibility(View.GONE);
637                }
638                else {
639                    mNextButton.setText(buttonText);
640                }
641            }
642            if (intent.hasExtra(EXTRA_PREFS_SET_BACK_TEXT)) {
643                String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_BACK_TEXT);
644                if (TextUtils.isEmpty(buttonText)) {
645                    backButton.setVisibility(View.GONE);
646                }
647                else {
648                    backButton.setText(buttonText);
649                }
650            }
651            if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_SKIP, false)) {
652                skipButton.setVisibility(View.VISIBLE);
653            }
654        }
655    }
656
657    /**
658     * Returns true if this activity is currently showing the header list.
659     */
660    public boolean hasHeaders() {
661        return getListView().getVisibility() == View.VISIBLE
662                && mPreferenceManager == null;
663    }
664
665    /**
666     * Returns the Header list
667     * @hide
668     */
669    public List<Header> getHeaders() {
670        return mHeaders;
671    }
672
673    /**
674     * Returns true if this activity is showing multiple panes -- the headers
675     * and a preference fragment.
676     */
677    public boolean isMultiPane() {
678        return hasHeaders() && mPrefsContainer.getVisibility() == View.VISIBLE;
679    }
680
681    /**
682     * Called to determine if the activity should run in multi-pane mode.
683     * The default implementation returns true if the screen is large
684     * enough.
685     */
686    public boolean onIsMultiPane() {
687        boolean preferMultiPane = getResources().getBoolean(
688                com.android.internal.R.bool.preferences_prefer_dual_pane);
689        return preferMultiPane;
690    }
691
692    /**
693     * Called to determine whether the header list should be hidden.
694     * The default implementation returns the
695     * value given in {@link #EXTRA_NO_HEADERS} or false if it is not supplied.
696     * This is set to false, for example, when the activity is being re-launched
697     * to show a particular preference activity.
698     */
699    public boolean onIsHidingHeaders() {
700        return getIntent().getBooleanExtra(EXTRA_NO_HEADERS, false);
701    }
702
703    /**
704     * Called to determine the initial header to be shown.  The default
705     * implementation simply returns the fragment of the first header.  Note
706     * that the returned Header object does not actually need to exist in
707     * your header list -- whatever its fragment is will simply be used to
708     * show for the initial UI.
709     */
710    public Header onGetInitialHeader() {
711        for (int i=0; i<mHeaders.size(); i++) {
712            Header h = mHeaders.get(i);
713            if (h.fragment != null) {
714                return h;
715            }
716        }
717        throw new IllegalStateException("Must have at least one header with a fragment");
718    }
719
720    /**
721     * Called after the header list has been updated ({@link #onBuildHeaders}
722     * has been called and returned due to {@link #invalidateHeaders()}) to
723     * specify the header that should now be selected.  The default implementation
724     * returns null to keep whatever header is currently selected.
725     */
726    public Header onGetNewHeader() {
727        return null;
728    }
729
730    /**
731     * Called when the activity needs its list of headers build.  By
732     * implementing this and adding at least one item to the list, you
733     * will cause the activity to run in its modern fragment mode.  Note
734     * that this function may not always be called; for example, if the
735     * activity has been asked to display a particular fragment without
736     * the header list, there is no need to build the headers.
737     *
738     * <p>Typical implementations will use {@link #loadHeadersFromResource}
739     * to fill in the list from a resource.
740     *
741     * @param target The list in which to place the headers.
742     */
743    public void onBuildHeaders(List<Header> target) {
744        // Should be overloaded by subclasses
745    }
746
747    /**
748     * Call when you need to change the headers being displayed.  Will result
749     * in onBuildHeaders() later being called to retrieve the new list.
750     */
751    public void invalidateHeaders() {
752        if (!mHandler.hasMessages(MSG_BUILD_HEADERS)) {
753            mHandler.sendEmptyMessage(MSG_BUILD_HEADERS);
754        }
755    }
756
757    /**
758     * Parse the given XML file as a header description, adding each
759     * parsed Header into the target list.
760     *
761     * @param resid The XML resource to load and parse.
762     * @param target The list in which the parsed headers should be placed.
763     */
764    public void loadHeadersFromResource(int resid, List<Header> target) {
765        XmlResourceParser parser = null;
766        try {
767            parser = getResources().getXml(resid);
768            AttributeSet attrs = Xml.asAttributeSet(parser);
769
770            int type;
771            while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
772                    && type != XmlPullParser.START_TAG) {
773                // Parse next until start tag is found
774            }
775
776            String nodeName = parser.getName();
777            if (!"preference-headers".equals(nodeName)) {
778                throw new RuntimeException(
779                        "XML document must start with <preference-headers> tag; found"
780                        + nodeName + " at " + parser.getPositionDescription());
781            }
782
783            Bundle curBundle = null;
784
785            final int outerDepth = parser.getDepth();
786            while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
787                   && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
788                if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
789                    continue;
790                }
791
792                nodeName = parser.getName();
793                if ("header".equals(nodeName)) {
794                    Header header = new Header();
795
796                    TypedArray sa = getResources().obtainAttributes(attrs,
797                            com.android.internal.R.styleable.PreferenceHeader);
798                    header.id = sa.getResourceId(
799                            com.android.internal.R.styleable.PreferenceHeader_id,
800                            (int)HEADER_ID_UNDEFINED);
801                    TypedValue tv = sa.peekValue(
802                            com.android.internal.R.styleable.PreferenceHeader_title);
803                    if (tv != null && tv.type == TypedValue.TYPE_STRING) {
804                        if (tv.resourceId != 0) {
805                            header.titleRes = tv.resourceId;
806                        } else {
807                            header.title = tv.string;
808                        }
809                    }
810                    tv = sa.peekValue(
811                            com.android.internal.R.styleable.PreferenceHeader_summary);
812                    if (tv != null && tv.type == TypedValue.TYPE_STRING) {
813                        if (tv.resourceId != 0) {
814                            header.summaryRes = tv.resourceId;
815                        } else {
816                            header.summary = tv.string;
817                        }
818                    }
819                    tv = sa.peekValue(
820                            com.android.internal.R.styleable.PreferenceHeader_breadCrumbTitle);
821                    if (tv != null && tv.type == TypedValue.TYPE_STRING) {
822                        if (tv.resourceId != 0) {
823                            header.breadCrumbTitleRes = tv.resourceId;
824                        } else {
825                            header.breadCrumbTitle = tv.string;
826                        }
827                    }
828                    tv = sa.peekValue(
829                            com.android.internal.R.styleable.PreferenceHeader_breadCrumbShortTitle);
830                    if (tv != null && tv.type == TypedValue.TYPE_STRING) {
831                        if (tv.resourceId != 0) {
832                            header.breadCrumbShortTitleRes = tv.resourceId;
833                        } else {
834                            header.breadCrumbShortTitle = tv.string;
835                        }
836                    }
837                    header.iconRes = sa.getResourceId(
838                            com.android.internal.R.styleable.PreferenceHeader_icon, 0);
839                    header.fragment = sa.getString(
840                            com.android.internal.R.styleable.PreferenceHeader_fragment);
841                    sa.recycle();
842
843                    if (curBundle == null) {
844                        curBundle = new Bundle();
845                    }
846
847                    final int innerDepth = parser.getDepth();
848                    while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
849                           && (type != XmlPullParser.END_TAG || parser.getDepth() > innerDepth)) {
850                        if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
851                            continue;
852                        }
853
854                        String innerNodeName = parser.getName();
855                        if (innerNodeName.equals("extra")) {
856                            getResources().parseBundleExtra("extra", attrs, curBundle);
857                            XmlUtils.skipCurrentTag(parser);
858
859                        } else if (innerNodeName.equals("intent")) {
860                            header.intent = Intent.parseIntent(getResources(), parser, attrs);
861
862                        } else {
863                            XmlUtils.skipCurrentTag(parser);
864                        }
865                    }
866
867                    if (curBundle.size() > 0) {
868                        header.fragmentArguments = curBundle;
869                        curBundle = null;
870                    }
871
872                    target.add(header);
873                } else {
874                    XmlUtils.skipCurrentTag(parser);
875                }
876            }
877
878        } catch (XmlPullParserException e) {
879            throw new RuntimeException("Error parsing headers", e);
880        } catch (IOException e) {
881            throw new RuntimeException("Error parsing headers", e);
882        } finally {
883            if (parser != null) parser.close();
884        }
885    }
886
887    /**
888     * Subclasses should override this method and verify that the given fragment is a valid type
889     * to be attached to this activity. The default implementation returns <code>true</code> for
890     * apps built for <code>android:targetSdkVersion</code> older than
891     * {@link android.os.Build.VERSION_CODES#KITKAT}. For later versions, it will throw an exception.
892     * @param fragmentName the class name of the Fragment about to be attached to this activity.
893     * @return true if the fragment class name is valid for this Activity and false otherwise.
894     */
895    protected boolean isValidFragment(String fragmentName) {
896        if (getApplicationInfo().targetSdkVersion  >= android.os.Build.VERSION_CODES.KITKAT) {
897            throw new RuntimeException(
898                    "Subclasses of PreferenceActivity must override isValidFragment(String)"
899                    + " to verify that the Fragment class is valid! " + this.getClass().getName()
900                    + " has not checked if fragment " + fragmentName + " is valid.");
901        } else {
902            return true;
903        }
904    }
905
906    /**
907     * Set a footer that should be shown at the bottom of the header list.
908     */
909    public void setListFooter(View view) {
910        mListFooter.removeAllViews();
911        mListFooter.addView(view, new FrameLayout.LayoutParams(
912                FrameLayout.LayoutParams.MATCH_PARENT,
913                FrameLayout.LayoutParams.WRAP_CONTENT));
914    }
915
916    @Override
917    protected void onStop() {
918        super.onStop();
919
920        if (mPreferenceManager != null) {
921            mPreferenceManager.dispatchActivityStop();
922        }
923    }
924
925    @Override
926    protected void onDestroy() {
927        mHandler.removeMessages(MSG_BIND_PREFERENCES);
928        mHandler.removeMessages(MSG_BUILD_HEADERS);
929        super.onDestroy();
930
931        if (mPreferenceManager != null) {
932            mPreferenceManager.dispatchActivityDestroy();
933        }
934    }
935
936    @Override
937    protected void onSaveInstanceState(Bundle outState) {
938        super.onSaveInstanceState(outState);
939
940        if (mHeaders.size() > 0) {
941            outState.putParcelableArrayList(HEADERS_TAG, mHeaders);
942            if (mCurHeader != null) {
943                int index = mHeaders.indexOf(mCurHeader);
944                if (index >= 0) {
945                    outState.putInt(CUR_HEADER_TAG, index);
946                }
947            }
948        }
949
950        if (mPreferenceManager != null) {
951            final PreferenceScreen preferenceScreen = getPreferenceScreen();
952            if (preferenceScreen != null) {
953                Bundle container = new Bundle();
954                preferenceScreen.saveHierarchyState(container);
955                outState.putBundle(PREFERENCES_TAG, container);
956            }
957        }
958    }
959
960    @Override
961    protected void onRestoreInstanceState(Bundle state) {
962        if (mPreferenceManager != null) {
963            Bundle container = state.getBundle(PREFERENCES_TAG);
964            if (container != null) {
965                final PreferenceScreen preferenceScreen = getPreferenceScreen();
966                if (preferenceScreen != null) {
967                    preferenceScreen.restoreHierarchyState(container);
968                    mSavedInstanceState = state;
969                    return;
970                }
971            }
972        }
973
974        // Only call this if we didn't save the instance state for later.
975        // If we did save it, it will be restored when we bind the adapter.
976        super.onRestoreInstanceState(state);
977    }
978
979    @Override
980    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
981        super.onActivityResult(requestCode, resultCode, data);
982
983        if (mPreferenceManager != null) {
984            mPreferenceManager.dispatchActivityResult(requestCode, resultCode, data);
985        }
986    }
987
988    @Override
989    public void onContentChanged() {
990        super.onContentChanged();
991
992        if (mPreferenceManager != null) {
993            postBindPreferences();
994        }
995    }
996
997    @Override
998    protected void onListItemClick(ListView l, View v, int position, long id) {
999        if (!isResumed()) {
1000            return;
1001        }
1002        super.onListItemClick(l, v, position, id);
1003
1004        if (mAdapter != null) {
1005            Object item = mAdapter.getItem(position);
1006            if (item instanceof Header) onHeaderClick((Header) item, position);
1007        }
1008    }
1009
1010    /**
1011     * Called when the user selects an item in the header list.  The default
1012     * implementation will call either
1013     * {@link #startWithFragment(String, Bundle, Fragment, int, int, int)}
1014     * or {@link #switchToHeader(Header)} as appropriate.
1015     *
1016     * @param header The header that was selected.
1017     * @param position The header's position in the list.
1018     */
1019    public void onHeaderClick(Header header, int position) {
1020        if (header.fragment != null) {
1021            if (mSinglePane) {
1022                int titleRes = header.breadCrumbTitleRes;
1023                int shortTitleRes = header.breadCrumbShortTitleRes;
1024                if (titleRes == 0) {
1025                    titleRes = header.titleRes;
1026                    shortTitleRes = 0;
1027                }
1028                startWithFragment(header.fragment, header.fragmentArguments, null, 0,
1029                        titleRes, shortTitleRes);
1030            } else {
1031                switchToHeader(header);
1032            }
1033        } else if (header.intent != null) {
1034            startActivity(header.intent);
1035        }
1036    }
1037
1038    /**
1039     * Called by {@link #startWithFragment(String, Bundle, Fragment, int, int, int)} when
1040     * in single-pane mode, to build an Intent to launch a new activity showing
1041     * the selected fragment.  The default implementation constructs an Intent
1042     * that re-launches the current activity with the appropriate arguments to
1043     * display the fragment.
1044     *
1045     * @param fragmentName The name of the fragment to display.
1046     * @param args Optional arguments to supply to the fragment.
1047     * @param titleRes Optional resource ID of title to show for this item.
1048     * @param shortTitleRes Optional resource ID of short title to show for this item.
1049     * @return Returns an Intent that can be launched to display the given
1050     * fragment.
1051     */
1052    public Intent onBuildStartFragmentIntent(String fragmentName, Bundle args,
1053            int titleRes, int shortTitleRes) {
1054        Intent intent = new Intent(Intent.ACTION_MAIN);
1055        intent.setClass(this, getClass());
1056        intent.putExtra(EXTRA_SHOW_FRAGMENT, fragmentName);
1057        intent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
1058        intent.putExtra(EXTRA_SHOW_FRAGMENT_TITLE, titleRes);
1059        intent.putExtra(EXTRA_SHOW_FRAGMENT_SHORT_TITLE, shortTitleRes);
1060        intent.putExtra(EXTRA_NO_HEADERS, true);
1061        return intent;
1062    }
1063
1064    /**
1065     * Like {@link #startWithFragment(String, Bundle, Fragment, int, int, int)}
1066     * but uses a 0 titleRes.
1067     */
1068    public void startWithFragment(String fragmentName, Bundle args,
1069            Fragment resultTo, int resultRequestCode) {
1070        startWithFragment(fragmentName, args, resultTo, resultRequestCode, 0, 0);
1071    }
1072
1073    /**
1074     * Start a new instance of this activity, showing only the given
1075     * preference fragment.  When launched in this mode, the header list
1076     * will be hidden and the given preference fragment will be instantiated
1077     * and fill the entire activity.
1078     *
1079     * @param fragmentName The name of the fragment to display.
1080     * @param args Optional arguments to supply to the fragment.
1081     * @param resultTo Option fragment that should receive the result of
1082     * the activity launch.
1083     * @param resultRequestCode If resultTo is non-null, this is the request
1084     * code in which to report the result.
1085     * @param titleRes Resource ID of string to display for the title of
1086     * this set of preferences.
1087     * @param shortTitleRes Resource ID of string to display for the short title of
1088     * this set of preferences.
1089     */
1090    public void startWithFragment(String fragmentName, Bundle args,
1091            Fragment resultTo, int resultRequestCode, int titleRes, int shortTitleRes) {
1092        Intent intent = onBuildStartFragmentIntent(fragmentName, args, titleRes, shortTitleRes);
1093        if (resultTo == null) {
1094            startActivity(intent);
1095        } else {
1096            resultTo.startActivityForResult(intent, resultRequestCode);
1097        }
1098    }
1099
1100    /**
1101     * Change the base title of the bread crumbs for the current preferences.
1102     * This will normally be called for you.  See
1103     * {@link android.app.FragmentBreadCrumbs} for more information.
1104     */
1105    public void showBreadCrumbs(CharSequence title, CharSequence shortTitle) {
1106        if (mFragmentBreadCrumbs == null) {
1107            View crumbs = findViewById(android.R.id.title);
1108            // For screens with a different kind of title, don't create breadcrumbs.
1109            try {
1110                mFragmentBreadCrumbs = (FragmentBreadCrumbs)crumbs;
1111            } catch (ClassCastException e) {
1112                setTitle(title);
1113                return;
1114            }
1115            if (mFragmentBreadCrumbs == null) {
1116                if (title != null) {
1117                    setTitle(title);
1118                }
1119                return;
1120            }
1121            if (mSinglePane) {
1122                mFragmentBreadCrumbs.setVisibility(View.GONE);
1123                // Hide the breadcrumb section completely for single-pane
1124                View bcSection = findViewById(com.android.internal.R.id.breadcrumb_section);
1125                if (bcSection != null) bcSection.setVisibility(View.GONE);
1126                setTitle(title);
1127            }
1128            mFragmentBreadCrumbs.setMaxVisible(2);
1129            mFragmentBreadCrumbs.setActivity(this);
1130        }
1131        if (mFragmentBreadCrumbs.getVisibility() != View.VISIBLE) {
1132            setTitle(title);
1133        } else {
1134            mFragmentBreadCrumbs.setTitle(title, shortTitle);
1135            mFragmentBreadCrumbs.setParentTitle(null, null, null);
1136        }
1137    }
1138
1139    /**
1140     * Should be called after onCreate to ensure that the breadcrumbs, if any, were created.
1141     * This prepends a title to the fragment breadcrumbs and attaches a listener to any clicks
1142     * on the parent entry.
1143     * @param title the title for the breadcrumb
1144     * @param shortTitle the short title for the breadcrumb
1145     */
1146    public void setParentTitle(CharSequence title, CharSequence shortTitle,
1147            OnClickListener listener) {
1148        if (mFragmentBreadCrumbs != null) {
1149            mFragmentBreadCrumbs.setParentTitle(title, shortTitle, listener);
1150        }
1151    }
1152
1153    void setSelectedHeader(Header header) {
1154        mCurHeader = header;
1155        int index = mHeaders.indexOf(header);
1156        if (index >= 0) {
1157            getListView().setItemChecked(index, true);
1158        } else {
1159            getListView().clearChoices();
1160        }
1161        showBreadCrumbs(header);
1162    }
1163
1164    void showBreadCrumbs(Header header) {
1165        if (header != null) {
1166            CharSequence title = header.getBreadCrumbTitle(getResources());
1167            if (title == null) title = header.getTitle(getResources());
1168            if (title == null) title = getTitle();
1169            showBreadCrumbs(title, header.getBreadCrumbShortTitle(getResources()));
1170        } else {
1171            showBreadCrumbs(getTitle(), null);
1172        }
1173    }
1174
1175    private void switchToHeaderInner(String fragmentName, Bundle args, int direction) {
1176        getFragmentManager().popBackStack(BACK_STACK_PREFS,
1177                FragmentManager.POP_BACK_STACK_INCLUSIVE);
1178        if (!isValidFragment(fragmentName)) {
1179            throw new IllegalArgumentException("Invalid fragment for this activity: "
1180                    + fragmentName);
1181        }
1182        Fragment f = Fragment.instantiate(this, fragmentName, args);
1183        FragmentTransaction transaction = getFragmentManager().beginTransaction();
1184        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
1185        transaction.replace(com.android.internal.R.id.prefs, f);
1186        transaction.commitAllowingStateLoss();
1187    }
1188
1189    /**
1190     * When in two-pane mode, switch the fragment pane to show the given
1191     * preference fragment.
1192     *
1193     * @param fragmentName The name of the fragment to display.
1194     * @param args Optional arguments to supply to the fragment.
1195     */
1196    public void switchToHeader(String fragmentName, Bundle args) {
1197        setSelectedHeader(null);
1198        switchToHeaderInner(fragmentName, args, 0);
1199    }
1200
1201    /**
1202     * When in two-pane mode, switch to the fragment pane to show the given
1203     * preference fragment.
1204     *
1205     * @param header The new header to display.
1206     */
1207    public void switchToHeader(Header header) {
1208        if (mCurHeader == header) {
1209            // This is the header we are currently displaying.  Just make sure
1210            // to pop the stack up to its root state.
1211            getFragmentManager().popBackStack(BACK_STACK_PREFS,
1212                    FragmentManager.POP_BACK_STACK_INCLUSIVE);
1213        } else {
1214            if (header.fragment == null) {
1215                throw new IllegalStateException("can't switch to header that has no fragment");
1216            }
1217            int direction = mHeaders.indexOf(header) - mHeaders.indexOf(mCurHeader);
1218            switchToHeaderInner(header.fragment, header.fragmentArguments, direction);
1219            setSelectedHeader(header);
1220        }
1221    }
1222
1223    Header findBestMatchingHeader(Header cur, ArrayList<Header> from) {
1224        ArrayList<Header> matches = new ArrayList<Header>();
1225        for (int j=0; j<from.size(); j++) {
1226            Header oh = from.get(j);
1227            if (cur == oh || (cur.id != HEADER_ID_UNDEFINED && cur.id == oh.id)) {
1228                // Must be this one.
1229                matches.clear();
1230                matches.add(oh);
1231                break;
1232            }
1233            if (cur.fragment != null) {
1234                if (cur.fragment.equals(oh.fragment)) {
1235                    matches.add(oh);
1236                }
1237            } else if (cur.intent != null) {
1238                if (cur.intent.equals(oh.intent)) {
1239                    matches.add(oh);
1240                }
1241            } else if (cur.title != null) {
1242                if (cur.title.equals(oh.title)) {
1243                    matches.add(oh);
1244                }
1245            }
1246        }
1247        final int NM = matches.size();
1248        if (NM == 1) {
1249            return matches.get(0);
1250        } else if (NM > 1) {
1251            for (int j=0; j<NM; j++) {
1252                Header oh = matches.get(j);
1253                if (cur.fragmentArguments != null &&
1254                        cur.fragmentArguments.equals(oh.fragmentArguments)) {
1255                    return oh;
1256                }
1257                if (cur.extras != null && cur.extras.equals(oh.extras)) {
1258                    return oh;
1259                }
1260                if (cur.title != null && cur.title.equals(oh.title)) {
1261                    return oh;
1262                }
1263            }
1264        }
1265        return null;
1266    }
1267
1268    /**
1269     * Start a new fragment.
1270     *
1271     * @param fragment The fragment to start
1272     * @param push If true, the current fragment will be pushed onto the back stack.  If false,
1273     * the current fragment will be replaced.
1274     */
1275    public void startPreferenceFragment(Fragment fragment, boolean push) {
1276        FragmentTransaction transaction = getFragmentManager().beginTransaction();
1277        transaction.replace(com.android.internal.R.id.prefs, fragment);
1278        if (push) {
1279            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
1280            transaction.addToBackStack(BACK_STACK_PREFS);
1281        } else {
1282            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
1283        }
1284        transaction.commitAllowingStateLoss();
1285    }
1286
1287    /**
1288     * Start a new fragment containing a preference panel.  If the preferences
1289     * are being displayed in multi-pane mode, the given fragment class will
1290     * be instantiated and placed in the appropriate pane.  If running in
1291     * single-pane mode, a new activity will be launched in which to show the
1292     * fragment.
1293     *
1294     * @param fragmentClass Full name of the class implementing the fragment.
1295     * @param args Any desired arguments to supply to the fragment.
1296     * @param titleRes Optional resource identifier of the title of this
1297     * fragment.
1298     * @param titleText Optional text of the title of this fragment.
1299     * @param resultTo Optional fragment that result data should be sent to.
1300     * If non-null, resultTo.onActivityResult() will be called when this
1301     * preference panel is done.  The launched panel must use
1302     * {@link #finishPreferencePanel(Fragment, int, Intent)} when done.
1303     * @param resultRequestCode If resultTo is non-null, this is the caller's
1304     * request code to be received with the resut.
1305     */
1306    public void startPreferencePanel(String fragmentClass, Bundle args, int titleRes,
1307            CharSequence titleText, Fragment resultTo, int resultRequestCode) {
1308        if (mSinglePane) {
1309            startWithFragment(fragmentClass, args, resultTo, resultRequestCode, titleRes, 0);
1310        } else {
1311            Fragment f = Fragment.instantiate(this, fragmentClass, args);
1312            if (resultTo != null) {
1313                f.setTargetFragment(resultTo, resultRequestCode);
1314            }
1315            FragmentTransaction transaction = getFragmentManager().beginTransaction();
1316            transaction.replace(com.android.internal.R.id.prefs, f);
1317            if (titleRes != 0) {
1318                transaction.setBreadCrumbTitle(titleRes);
1319            } else if (titleText != null) {
1320                transaction.setBreadCrumbTitle(titleText);
1321            }
1322            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
1323            transaction.addToBackStack(BACK_STACK_PREFS);
1324            transaction.commitAllowingStateLoss();
1325        }
1326    }
1327
1328    /**
1329     * Called by a preference panel fragment to finish itself.
1330     *
1331     * @param caller The fragment that is asking to be finished.
1332     * @param resultCode Optional result code to send back to the original
1333     * launching fragment.
1334     * @param resultData Optional result data to send back to the original
1335     * launching fragment.
1336     */
1337    public void finishPreferencePanel(Fragment caller, int resultCode, Intent resultData) {
1338        if (mSinglePane) {
1339            setResult(resultCode, resultData);
1340            finish();
1341        } else {
1342            // XXX be smarter about popping the stack.
1343            onBackPressed();
1344            if (caller != null) {
1345                if (caller.getTargetFragment() != null) {
1346                    caller.getTargetFragment().onActivityResult(caller.getTargetRequestCode(),
1347                            resultCode, resultData);
1348                }
1349            }
1350        }
1351    }
1352
1353    @Override
1354    public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) {
1355        startPreferencePanel(pref.getFragment(), pref.getExtras(), pref.getTitleRes(),
1356                pref.getTitle(), null, 0);
1357        return true;
1358    }
1359
1360    /**
1361     * Posts a message to bind the preferences to the list view.
1362     * <p>
1363     * Binding late is preferred as any custom preference types created in
1364     * {@link #onCreate(Bundle)} are able to have their views recycled.
1365     */
1366    private void postBindPreferences() {
1367        if (mHandler.hasMessages(MSG_BIND_PREFERENCES)) return;
1368        mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget();
1369    }
1370
1371    private void bindPreferences() {
1372        final PreferenceScreen preferenceScreen = getPreferenceScreen();
1373        if (preferenceScreen != null) {
1374            preferenceScreen.bind(getListView());
1375            if (mSavedInstanceState != null) {
1376                super.onRestoreInstanceState(mSavedInstanceState);
1377                mSavedInstanceState = null;
1378            }
1379        }
1380    }
1381
1382    /**
1383     * Returns the {@link PreferenceManager} used by this activity.
1384     * @return The {@link PreferenceManager}.
1385     *
1386     * @deprecated This function is not relevant for a modern fragment-based
1387     * PreferenceActivity.
1388     */
1389    @Deprecated
1390    public PreferenceManager getPreferenceManager() {
1391        return mPreferenceManager;
1392    }
1393
1394    private void requirePreferenceManager() {
1395        if (mPreferenceManager == null) {
1396            if (mAdapter == null) {
1397                throw new RuntimeException("This should be called after super.onCreate.");
1398            }
1399            throw new RuntimeException(
1400                    "Modern two-pane PreferenceActivity requires use of a PreferenceFragment");
1401        }
1402    }
1403
1404    /**
1405     * Sets the root of the preference hierarchy that this activity is showing.
1406     *
1407     * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.
1408     *
1409     * @deprecated This function is not relevant for a modern fragment-based
1410     * PreferenceActivity.
1411     */
1412    @Deprecated
1413    public void setPreferenceScreen(PreferenceScreen preferenceScreen) {
1414        requirePreferenceManager();
1415
1416        if (mPreferenceManager.setPreferences(preferenceScreen) && preferenceScreen != null) {
1417            postBindPreferences();
1418            CharSequence title = getPreferenceScreen().getTitle();
1419            // Set the title of the activity
1420            if (title != null) {
1421                setTitle(title);
1422            }
1423        }
1424    }
1425
1426    /**
1427     * Gets the root of the preference hierarchy that this activity is showing.
1428     *
1429     * @return The {@link PreferenceScreen} that is the root of the preference
1430     *         hierarchy.
1431     *
1432     * @deprecated This function is not relevant for a modern fragment-based
1433     * PreferenceActivity.
1434     */
1435    @Deprecated
1436    public PreferenceScreen getPreferenceScreen() {
1437        if (mPreferenceManager != null) {
1438            return mPreferenceManager.getPreferenceScreen();
1439        }
1440        return null;
1441    }
1442
1443    /**
1444     * Adds preferences from activities that match the given {@link Intent}.
1445     *
1446     * @param intent The {@link Intent} to query activities.
1447     *
1448     * @deprecated This function is not relevant for a modern fragment-based
1449     * PreferenceActivity.
1450     */
1451    @Deprecated
1452    public void addPreferencesFromIntent(Intent intent) {
1453        requirePreferenceManager();
1454
1455        setPreferenceScreen(mPreferenceManager.inflateFromIntent(intent, getPreferenceScreen()));
1456    }
1457
1458    /**
1459     * Inflates the given XML resource and adds the preference hierarchy to the current
1460     * preference hierarchy.
1461     *
1462     * @param preferencesResId The XML resource ID to inflate.
1463     *
1464     * @deprecated This function is not relevant for a modern fragment-based
1465     * PreferenceActivity.
1466     */
1467    @Deprecated
1468    public void addPreferencesFromResource(int preferencesResId) {
1469        requirePreferenceManager();
1470
1471        setPreferenceScreen(mPreferenceManager.inflateFromResource(this, preferencesResId,
1472                getPreferenceScreen()));
1473    }
1474
1475    /**
1476     * {@inheritDoc}
1477     *
1478     * @deprecated This function is not relevant for a modern fragment-based
1479     * PreferenceActivity.
1480     */
1481    @Deprecated
1482    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
1483        return false;
1484    }
1485
1486    /**
1487     * Finds a {@link Preference} based on its key.
1488     *
1489     * @param key The key of the preference to retrieve.
1490     * @return The {@link Preference} with the key, or null.
1491     * @see PreferenceGroup#findPreference(CharSequence)
1492     *
1493     * @deprecated This function is not relevant for a modern fragment-based
1494     * PreferenceActivity.
1495     */
1496    @Deprecated
1497    public Preference findPreference(CharSequence key) {
1498
1499        if (mPreferenceManager == null) {
1500            return null;
1501        }
1502
1503        return mPreferenceManager.findPreference(key);
1504    }
1505
1506    @Override
1507    protected void onNewIntent(Intent intent) {
1508        if (mPreferenceManager != null) {
1509            mPreferenceManager.dispatchNewIntent(intent);
1510        }
1511    }
1512
1513    // give subclasses access to the Next button
1514    /** @hide */
1515    protected boolean hasNextButton() {
1516        return mNextButton != null;
1517    }
1518    /** @hide */
1519    protected Button getNextButton() {
1520        return mNextButton;
1521    }
1522}
1523