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