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