[go: nahoru, domu]

1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.preference;
18
19import android.annotation.Nullable;
20import android.annotation.XmlRes;
21import android.app.Activity;
22import android.app.Fragment;
23import android.content.Intent;
24import android.content.SharedPreferences;
25import android.content.res.TypedArray;
26import android.graphics.drawable.Drawable;
27import android.os.Bundle;
28import android.os.Handler;
29import android.os.Message;
30import android.view.KeyEvent;
31import android.view.LayoutInflater;
32import android.view.View;
33import android.view.View.OnKeyListener;
34import android.view.ViewGroup;
35import android.widget.ListView;
36
37/**
38 * Shows a hierarchy of {@link Preference} objects as
39 * lists. These preferences will
40 * automatically save to {@link SharedPreferences} as the user interacts with
41 * them. To retrieve an instance of {@link SharedPreferences} that the
42 * preference hierarchy in this fragment will use, call
43 * {@link PreferenceManager#getDefaultSharedPreferences(android.content.Context)}
44 * with a context in the same package as this fragment.
45 * <p>
46 * Furthermore, the preferences shown will follow the visual style of system
47 * preferences. It is easy to create a hierarchy of preferences (that can be
48 * shown on multiple screens) via XML. For these reasons, it is recommended to
49 * use this fragment (as a superclass) to deal with preferences in applications.
50 * <p>
51 * A {@link PreferenceScreen} object should be at the top of the preference
52 * hierarchy. Furthermore, subsequent {@link PreferenceScreen} in the hierarchy
53 * denote a screen break--that is the preferences contained within subsequent
54 * {@link PreferenceScreen} should be shown on another screen. The preference
55 * framework handles showing these other screens from the preference hierarchy.
56 * <p>
57 * The preference hierarchy can be formed in multiple ways:
58 * <li> From an XML file specifying the hierarchy
59 * <li> From different {@link Activity Activities} that each specify its own
60 * preferences in an XML file via {@link Activity} meta-data
61 * <li> From an object hierarchy rooted with {@link PreferenceScreen}
62 * <p>
63 * To inflate from XML, use the {@link #addPreferencesFromResource(int)}. The
64 * root element should be a {@link PreferenceScreen}. Subsequent elements can point
65 * to actual {@link Preference} subclasses. As mentioned above, subsequent
66 * {@link PreferenceScreen} in the hierarchy will result in the screen break.
67 * <p>
68 * To specify an {@link Intent} to query {@link Activity Activities} that each
69 * have preferences, use {@link #addPreferencesFromIntent}. Each
70 * {@link Activity} can specify meta-data in the manifest (via the key
71 * {@link PreferenceManager#METADATA_KEY_PREFERENCES}) that points to an XML
72 * resource. These XML resources will be inflated into a single preference
73 * hierarchy and shown by this fragment.
74 * <p>
75 * To specify an object hierarchy rooted with {@link PreferenceScreen}, use
76 * {@link #setPreferenceScreen(PreferenceScreen)}.
77 * <p>
78 * As a convenience, this fragment implements a click listener for any
79 * preference in the current hierarchy, see
80 * {@link #onPreferenceTreeClick(PreferenceScreen, Preference)}.
81 *
82 * <div class="special reference">
83 * <h3>Developer Guides</h3>
84 * <p>For information about using {@code PreferenceFragment},
85 * read the <a href="{@docRoot}guide/topics/ui/settings.html">Settings</a>
86 * guide.</p>
87 * </div>
88 *
89 * <a name="SampleCode"></a>
90 * <h3>Sample Code</h3>
91 *
92 * <p>The following sample code shows a simple preference fragment that is
93 * populated from a resource.  The resource it loads is:</p>
94 *
95 * {@sample development/samples/ApiDemos/res/xml/preferences.xml preferences}
96 *
97 * <p>The fragment implementation itself simply populates the preferences
98 * when created.  Note that the preferences framework takes care of loading
99 * the current values out of the app preferences and writing them when changed:</p>
100 *
101 * {@sample development/samples/ApiDemos/src/com/example/android/apis/preference/FragmentPreferences.java
102 *      fragment}
103 *
104 * @see Preference
105 * @see PreferenceScreen
106 */
107public abstract class PreferenceFragment extends Fragment implements
108        PreferenceManager.OnPreferenceTreeClickListener {
109
110    private static final String PREFERENCES_TAG = "android:preferences";
111
112    private PreferenceManager mPreferenceManager;
113    private ListView mList;
114    private boolean mHavePrefs;
115    private boolean mInitDone;
116
117    private int mLayoutResId = com.android.internal.R.layout.preference_list_fragment;
118
119    /**
120     * The starting request code given out to preference framework.
121     */
122    private static final int FIRST_REQUEST_CODE = 100;
123
124    private static final int MSG_BIND_PREFERENCES = 1;
125    private Handler mHandler = new Handler() {
126        @Override
127        public void handleMessage(Message msg) {
128            switch (msg.what) {
129
130                case MSG_BIND_PREFERENCES:
131                    bindPreferences();
132                    break;
133            }
134        }
135    };
136
137    final private Runnable mRequestFocus = new Runnable() {
138        public void run() {
139            mList.focusableViewAvailable(mList);
140        }
141    };
142
143    /**
144     * Interface that PreferenceFragment's containing activity should
145     * implement to be able to process preference items that wish to
146     * switch to a new fragment.
147     */
148    public interface OnPreferenceStartFragmentCallback {
149        /**
150         * Called when the user has clicked on a Preference that has
151         * a fragment class name associated with it.  The implementation
152         * to should instantiate and switch to an instance of the given
153         * fragment.
154         */
155        boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref);
156    }
157
158    @Override
159    public void onCreate(@Nullable Bundle savedInstanceState) {
160        super.onCreate(savedInstanceState);
161        mPreferenceManager = new PreferenceManager(getActivity(), FIRST_REQUEST_CODE);
162        mPreferenceManager.setFragment(this);
163    }
164
165    @Override
166    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
167            @Nullable Bundle savedInstanceState) {
168
169        TypedArray a = getActivity().obtainStyledAttributes(null,
170                com.android.internal.R.styleable.PreferenceFragment,
171                com.android.internal.R.attr.preferenceFragmentStyle,
172                0);
173
174        mLayoutResId = a.getResourceId(com.android.internal.R.styleable.PreferenceFragment_layout,
175                mLayoutResId);
176
177        a.recycle();
178
179        return inflater.inflate(mLayoutResId, container, false);
180    }
181
182    @Override
183    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
184        super.onViewCreated(view, savedInstanceState);
185
186        TypedArray a = getActivity().obtainStyledAttributes(null,
187                com.android.internal.R.styleable.PreferenceFragment,
188                com.android.internal.R.attr.preferenceFragmentStyle,
189                0);
190
191        ListView lv = (ListView) view.findViewById(android.R.id.list);
192        if (lv != null) {
193            Drawable divider =
194                    a.getDrawable(com.android.internal.R.styleable.PreferenceFragment_divider);
195            if (divider != null) {
196                lv.setDivider(divider);
197            }
198        }
199
200        a.recycle();
201    }
202
203    @Override
204    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
205        super.onActivityCreated(savedInstanceState);
206
207        if (mHavePrefs) {
208            bindPreferences();
209        }
210
211        mInitDone = true;
212
213        if (savedInstanceState != null) {
214            Bundle container = savedInstanceState.getBundle(PREFERENCES_TAG);
215            if (container != null) {
216                final PreferenceScreen preferenceScreen = getPreferenceScreen();
217                if (preferenceScreen != null) {
218                    preferenceScreen.restoreHierarchyState(container);
219                }
220            }
221        }
222    }
223
224    @Override
225    public void onStart() {
226        super.onStart();
227        mPreferenceManager.setOnPreferenceTreeClickListener(this);
228    }
229
230    @Override
231    public void onStop() {
232        super.onStop();
233        mPreferenceManager.dispatchActivityStop();
234        mPreferenceManager.setOnPreferenceTreeClickListener(null);
235    }
236
237    @Override
238    public void onDestroyView() {
239        if (mList != null) {
240            mList.setOnKeyListener(null);
241        }
242        mList = null;
243        mHandler.removeCallbacks(mRequestFocus);
244        mHandler.removeMessages(MSG_BIND_PREFERENCES);
245        super.onDestroyView();
246    }
247
248    @Override
249    public void onDestroy() {
250        super.onDestroy();
251        mPreferenceManager.dispatchActivityDestroy();
252    }
253
254    @Override
255    public void onSaveInstanceState(Bundle outState) {
256        super.onSaveInstanceState(outState);
257
258        final PreferenceScreen preferenceScreen = getPreferenceScreen();
259        if (preferenceScreen != null) {
260            Bundle container = new Bundle();
261            preferenceScreen.saveHierarchyState(container);
262            outState.putBundle(PREFERENCES_TAG, container);
263        }
264    }
265
266    @Override
267    public void onActivityResult(int requestCode, int resultCode, Intent data) {
268        super.onActivityResult(requestCode, resultCode, data);
269
270        mPreferenceManager.dispatchActivityResult(requestCode, resultCode, data);
271    }
272
273    /**
274     * Returns the {@link PreferenceManager} used by this fragment.
275     * @return The {@link PreferenceManager}.
276     */
277    public PreferenceManager getPreferenceManager() {
278        return mPreferenceManager;
279    }
280
281    /**
282     * Sets the root of the preference hierarchy that this fragment is showing.
283     *
284     * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.
285     */
286    public void setPreferenceScreen(PreferenceScreen preferenceScreen) {
287        if (mPreferenceManager.setPreferences(preferenceScreen) && preferenceScreen != null) {
288            onUnbindPreferences();
289            mHavePrefs = true;
290            if (mInitDone) {
291                postBindPreferences();
292            }
293        }
294    }
295
296    /**
297     * Gets the root of the preference hierarchy that this fragment is showing.
298     *
299     * @return The {@link PreferenceScreen} that is the root of the preference
300     *         hierarchy.
301     */
302    public PreferenceScreen getPreferenceScreen() {
303        return mPreferenceManager.getPreferenceScreen();
304    }
305
306    /**
307     * Adds preferences from activities that match the given {@link Intent}.
308     *
309     * @param intent The {@link Intent} to query activities.
310     */
311    public void addPreferencesFromIntent(Intent intent) {
312        requirePreferenceManager();
313
314        setPreferenceScreen(mPreferenceManager.inflateFromIntent(intent, getPreferenceScreen()));
315    }
316
317    /**
318     * Inflates the given XML resource and adds the preference hierarchy to the current
319     * preference hierarchy.
320     *
321     * @param preferencesResId The XML resource ID to inflate.
322     */
323    public void addPreferencesFromResource(@XmlRes int preferencesResId) {
324        requirePreferenceManager();
325
326        setPreferenceScreen(mPreferenceManager.inflateFromResource(getActivity(),
327                preferencesResId, getPreferenceScreen()));
328    }
329
330    /**
331     * {@inheritDoc}
332     */
333    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
334            Preference preference) {
335        if (preference.getFragment() != null &&
336                getActivity() instanceof OnPreferenceStartFragmentCallback) {
337            return ((OnPreferenceStartFragmentCallback)getActivity()).onPreferenceStartFragment(
338                    this, preference);
339        }
340        return false;
341    }
342
343    /**
344     * Finds a {@link Preference} based on its key.
345     *
346     * @param key The key of the preference to retrieve.
347     * @return The {@link Preference} with the key, or null.
348     * @see PreferenceGroup#findPreference(CharSequence)
349     */
350    public Preference findPreference(CharSequence key) {
351        if (mPreferenceManager == null) {
352            return null;
353        }
354        return mPreferenceManager.findPreference(key);
355    }
356
357    private void requirePreferenceManager() {
358        if (mPreferenceManager == null) {
359            throw new RuntimeException("This should be called after super.onCreate.");
360        }
361    }
362
363    private void postBindPreferences() {
364        if (mHandler.hasMessages(MSG_BIND_PREFERENCES)) return;
365        mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget();
366    }
367
368    private void bindPreferences() {
369        final PreferenceScreen preferenceScreen = getPreferenceScreen();
370        if (preferenceScreen != null) {
371            preferenceScreen.bind(getListView());
372        }
373        onBindPreferences();
374    }
375
376    /** @hide */
377    protected void onBindPreferences() {
378    }
379
380    /** @hide */
381    protected void onUnbindPreferences() {
382    }
383
384    /** @hide */
385    public ListView getListView() {
386        ensureList();
387        return mList;
388    }
389
390    /** @hide */
391    public boolean hasListView() {
392        if (mList != null) {
393            return true;
394        }
395        View root = getView();
396        if (root == null) {
397            return false;
398        }
399        View rawListView = root.findViewById(android.R.id.list);
400        if (!(rawListView instanceof ListView)) {
401            return false;
402        }
403        mList = (ListView)rawListView;
404        if (mList == null) {
405            return false;
406        }
407        return true;
408    }
409
410    private void ensureList() {
411        if (mList != null) {
412            return;
413        }
414        View root = getView();
415        if (root == null) {
416            throw new IllegalStateException("Content view not yet created");
417        }
418        View rawListView = root.findViewById(android.R.id.list);
419        if (!(rawListView instanceof ListView)) {
420            throw new RuntimeException(
421                    "Content has view with id attribute 'android.R.id.list' "
422                    + "that is not a ListView class");
423        }
424        mList = (ListView)rawListView;
425        if (mList == null) {
426            throw new RuntimeException(
427                    "Your content must have a ListView whose id attribute is " +
428                    "'android.R.id.list'");
429        }
430        mList.setOnKeyListener(mListOnKeyListener);
431        mHandler.post(mRequestFocus);
432    }
433
434    private OnKeyListener mListOnKeyListener = new OnKeyListener() {
435
436        @Override
437        public boolean onKey(View v, int keyCode, KeyEvent event) {
438            Object selectedItem = mList.getSelectedItem();
439            if (selectedItem instanceof Preference) {
440                View selectedView = mList.getSelectedView();
441                return ((Preference)selectedItem).onKey(
442                        selectedView, keyCode, event);
443            }
444            return false;
445        }
446
447    };
448}
449