PreferenceScreen.java revision 1560003d4a1a0ce36bb288905a6a317c1fd74b32
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.Dialog;
20import android.content.Context;
21import android.content.DialogInterface;
22import android.os.Bundle;
23import android.os.Parcel;
24import android.os.Parcelable;
25import android.text.TextUtils;
26import android.util.AttributeSet;
27import android.view.View;
28import android.widget.Adapter;
29import android.widget.AdapterView;
30import android.widget.ListAdapter;
31import android.widget.ListView;
32
33/**
34 * Represents a top-level {@link Preference} that
35 * is the root of a Preference hierarchy. A {@link PreferenceActivity}
36 * points to an instance of this class to show the preferences. To instantiate
37 * this class, use {@link PreferenceManager#createPreferenceScreen(Context)}.
38 * <ul>
39 * This class can appear in two places:
40 * <li> When a {@link PreferenceActivity} points to this, it is used as the root
41 * and is not shown (only the contained preferences are shown).
42 * <li> When it appears inside another preference hierarchy, it is shown and
43 * serves as the gateway to another screen of preferences (either by showing
44 * another screen of preferences as a {@link Dialog} or via a
45 * {@link Context#startActivity(android.content.Intent)} from the
46 * {@link Preference#getIntent()}). The children of this {@link PreferenceScreen}
47 * are NOT shown in the screen that this {@link PreferenceScreen} is shown in.
48 * Instead, a separate screen will be shown when this preference is clicked.
49 * </ul>
50 * <p>Here's an example XML layout of a PreferenceScreen:</p>
51 * <pre>
52&lt;PreferenceScreen
53        xmlns:android="http://schemas.android.com/apk/res/android"
54        android:key="first_preferencescreen"&gt;
55    &lt;CheckBoxPreference
56            android:key="wifi enabled"
57            android:title="WiFi" /&gt;
58    &lt;PreferenceScreen
59            android:key="second_preferencescreen"
60            android:title="WiFi settings"&gt;
61        &lt;CheckBoxPreference
62                android:key="prefer wifi"
63                android:title="Prefer WiFi" /&gt;
64        ... other preferences here ...
65    &lt;/PreferenceScreen&gt;
66&lt;/PreferenceScreen&gt; </pre>
67 * <p>
68 * In this example, the "first_preferencescreen" will be used as the root of the
69 * hierarchy and given to a {@link PreferenceActivity}. The first screen will
70 * show preferences "WiFi" (which can be used to quickly enable/disable WiFi)
71 * and "WiFi settings". The "WiFi settings" is the "second_preferencescreen" and when
72 * clicked will show another screen of preferences such as "Prefer WiFi" (and
73 * the other preferences that are children of the "second_preferencescreen" tag).
74 *
75 * @see PreferenceCategory
76 */
77public final class PreferenceScreen extends PreferenceGroup implements AdapterView.OnItemClickListener,
78        DialogInterface.OnDismissListener {
79
80    private ListAdapter mRootAdapter;
81
82    private Dialog mDialog;
83
84    private ListView mListView;
85
86    /**
87     * Do NOT use this constructor, use {@link PreferenceManager#createPreferenceScreen(Context)}.
88     * @hide-
89     */
90    public PreferenceScreen(Context context, AttributeSet attrs) {
91        super(context, attrs, com.android.internal.R.attr.preferenceScreenStyle);
92    }
93
94    /**
95     * Returns an adapter that can be attached to a {@link PreferenceActivity}
96     * or {@link PreferenceFragment} to show the preferences contained in this
97     * {@link PreferenceScreen}.
98     * <p>
99     * This {@link PreferenceScreen} will NOT appear in the returned adapter, instead
100     * it appears in the hierarchy above this {@link PreferenceScreen}.
101     * <p>
102     * This adapter's {@link Adapter#getItem(int)} should always return a
103     * subclass of {@link Preference}.
104     *
105     * @return An adapter that provides the {@link Preference} contained in this
106     *         {@link PreferenceScreen}.
107     */
108    public ListAdapter getRootAdapter() {
109        if (mRootAdapter == null) {
110            mRootAdapter = onCreateRootAdapter();
111        }
112
113        return mRootAdapter;
114    }
115
116    /**
117     * Creates the root adapter.
118     *
119     * @return An adapter that contains the preferences contained in this {@link PreferenceScreen}.
120     * @see #getRootAdapter()
121     */
122    protected ListAdapter onCreateRootAdapter() {
123        return new PreferenceGroupAdapter(this);
124    }
125
126    /**
127     * Binds a {@link ListView} to the preferences contained in this {@link PreferenceScreen} via
128     * {@link #getRootAdapter()}. It also handles passing list item clicks to the corresponding
129     * {@link Preference} contained by this {@link PreferenceScreen}.
130     *
131     * @param listView The list view to attach to.
132     */
133    public void bind(ListView listView) {
134        listView.setOnItemClickListener(this);
135        listView.setAdapter(getRootAdapter());
136
137        onAttachedToActivity();
138    }
139
140    @Override
141    protected void onClick() {
142        if (getIntent() != null || getFragment() != null || getPreferenceCount() == 0) {
143            return;
144        }
145
146        showDialog(null);
147    }
148
149    private void showDialog(Bundle state) {
150        Context context = getContext();
151        if (mListView != null) {
152            mListView.setAdapter(null);
153        }
154        mListView = new ListView(context);
155        bind(mListView);
156
157        // Set the title bar if title is available, else no title bar
158        final CharSequence title = getTitle();
159        Dialog dialog = mDialog = new Dialog(context, TextUtils.isEmpty(title)
160                ? com.android.internal.R.style.Theme_NoTitleBar
161                : com.android.internal.R.style.Theme);
162        dialog.setContentView(mListView);
163        if (!TextUtils.isEmpty(title)) {
164            dialog.setTitle(title);
165        }
166        dialog.setOnDismissListener(this);
167        if (state != null) {
168            dialog.onRestoreInstanceState(state);
169        }
170
171        // Add the screen to the list of preferences screens opened as dialogs
172        getPreferenceManager().addPreferencesScreen(dialog);
173
174        dialog.show();
175    }
176
177    public void onDismiss(DialogInterface dialog) {
178        mDialog = null;
179        getPreferenceManager().removePreferencesScreen(dialog);
180    }
181
182    /**
183     * Used to get a handle to the dialog.
184     * This is useful for cases where we want to manipulate the dialog
185     * as we would with any other activity or view.
186     */
187    public Dialog getDialog() {
188        return mDialog;
189    }
190
191    public void onItemClick(AdapterView parent, View view, int position, long id) {
192        Object item = getRootAdapter().getItem(position);
193        if (!(item instanceof Preference)) return;
194
195        final Preference preference = (Preference) item;
196        preference.performClick(this);
197    }
198
199    @Override
200    protected boolean isOnSameScreenAsChildren() {
201        return false;
202    }
203
204    @Override
205    protected Parcelable onSaveInstanceState() {
206        final Parcelable superState = super.onSaveInstanceState();
207        final Dialog dialog = mDialog;
208        if (dialog == null || !dialog.isShowing()) {
209            return superState;
210        }
211
212        final SavedState myState = new SavedState(superState);
213        myState.isDialogShowing = true;
214        myState.dialogBundle = dialog.onSaveInstanceState();
215        return myState;
216    }
217
218    @Override
219    protected void onRestoreInstanceState(Parcelable state) {
220        if (state == null || !state.getClass().equals(SavedState.class)) {
221            // Didn't save state for us in onSaveInstanceState
222            super.onRestoreInstanceState(state);
223            return;
224        }
225
226        SavedState myState = (SavedState) state;
227        super.onRestoreInstanceState(myState.getSuperState());
228        if (myState.isDialogShowing) {
229            showDialog(myState.dialogBundle);
230        }
231    }
232
233    private static class SavedState extends BaseSavedState {
234        boolean isDialogShowing;
235        Bundle dialogBundle;
236
237        public SavedState(Parcel source) {
238            super(source);
239            isDialogShowing = source.readInt() == 1;
240            dialogBundle = source.readBundle();
241        }
242
243        @Override
244        public void writeToParcel(Parcel dest, int flags) {
245            super.writeToParcel(dest, flags);
246            dest.writeInt(isDialogShowing ? 1 : 0);
247            dest.writeBundle(dialogBundle);
248        }
249
250        public SavedState(Parcelable superState) {
251            super(superState);
252        }
253
254        public static final Parcelable.Creator<SavedState> CREATOR =
255                new Parcelable.Creator<SavedState>() {
256            public SavedState createFromParcel(Parcel in) {
257                return new SavedState(in);
258            }
259
260            public SavedState[] newArray(int size) {
261                return new SavedState[size];
262            }
263        };
264    }
265
266}
267