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