blob: 3e496b6eb550b9bd7630961e9967cd8ae843c3d9 [file] [log] [blame]
Dianne Hackborn42c29362010-07-28 14:32:15 -07001/*
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
Scott Kennedy3c32b622015-02-22 16:58:58 -080019import android.annotation.Nullable;
Tor Norbye417ee5b2015-03-10 20:57:37 -070020import android.annotation.XmlRes;
Dianne Hackborn42c29362010-07-28 14:32:15 -070021import android.app.Activity;
22import android.app.Fragment;
23import android.content.Intent;
24import android.content.SharedPreferences;
Fabrice Di Megliof9499b32014-07-02 17:28:20 -070025import android.content.res.TypedArray;
Jason Monk7fc97c92015-10-28 14:33:39 -040026import android.graphics.drawable.Drawable;
Dianne Hackborn42c29362010-07-28 14:32:15 -070027import android.os.Bundle;
28import android.os.Handler;
29import android.os.Message;
John Reck014fea22011-06-15 16:46:36 -070030import android.view.KeyEvent;
Dianne Hackborn42c29362010-07-28 14:32:15 -070031import android.view.LayoutInflater;
32import android.view.View;
John Reck014fea22011-06-15 16:46:36 -070033import android.view.View.OnKeyListener;
Jason Monk7fc97c92015-10-28 14:33:39 -040034import android.view.ViewGroup;
Dianne Hackborn42c29362010-07-28 14:32:15 -070035import 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>
Dianne Hackbornb1ad5972010-08-02 17:30:33 -070046 * 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>
Dianne Hackborn42c29362010-07-28 14:32:15 -070057 * 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)}.
Scott Maincdd0c592012-07-26 17:03:51 -070081 *
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>
Dianne Hackborn42c29362010-07-28 14:32:15 -070088 *
89 * <a name="SampleCode"></a>
90 * <h3>Sample Code</h3>
91 *
Dianne Hackbornb1ad5972010-08-02 17:30:33 -070092 * <p>The following sample code shows a simple preference fragment that is
93 * populated from a resource. The resource it loads is:</p>
Dianne Hackborn42c29362010-07-28 14:32:15 -070094 *
Dianne Hackbornb1ad5972010-08-02 17:30:33 -070095 * {@sample development/samples/ApiDemos/res/xml/preferences.xml preferences}
Dianne Hackborn42c29362010-07-28 14:32:15 -070096 *
Dianne Hackbornb1ad5972010-08-02 17:30:33 -070097 * <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>
Dianne Hackborn42c29362010-07-28 14:32:15 -0700100 *
Dianne Hackbornb1ad5972010-08-02 17:30:33 -0700101 * {@sample development/samples/ApiDemos/src/com/example/android/apis/preference/FragmentPreferences.java
102 * fragment}
Dianne Hackborn42c29362010-07-28 14:32:15 -0700103 *
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
Fabrice Di Megliof9499b32014-07-02 17:28:20 -0700117 private int mLayoutResId = com.android.internal.R.layout.preference_list_fragment;
118
Dianne Hackborn42c29362010-07-28 14:32:15 -0700119 /**
120 * The starting request code given out to preference framework.
121 */
122 private static final int FIRST_REQUEST_CODE = 100;
123
Dianne Hackborn3e449ce2010-09-11 20:52:31 -0700124 private static final int MSG_BIND_PREFERENCES = 1;
Dianne Hackborn42c29362010-07-28 14:32:15 -0700125 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
Dianne Hackbornb3cf10f2010-08-03 13:07:11 -0700143 /**
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
Dianne Hackborn42c29362010-07-28 14:32:15 -0700158 @Override
Scott Kennedy3c32b622015-02-22 16:58:58 -0800159 public void onCreate(@Nullable Bundle savedInstanceState) {
Dianne Hackborn42c29362010-07-28 14:32:15 -0700160 super.onCreate(savedInstanceState);
161 mPreferenceManager = new PreferenceManager(getActivity(), FIRST_REQUEST_CODE);
Amith Yamasani82e7bc12010-09-23 15:07:58 -0700162 mPreferenceManager.setFragment(this);
Dianne Hackborn42c29362010-07-28 14:32:15 -0700163 }
164
165 @Override
Scott Kennedy3c32b622015-02-22 16:58:58 -0800166 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
167 @Nullable Bundle savedInstanceState) {
Fabrice Di Megliof9499b32014-07-02 17:28:20 -0700168
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);
Dianne Hackborn42c29362010-07-28 14:32:15 -0700180 }
181
182 @Override
Jason Monk7fc97c92015-10-28 14:33:39 -0400183 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
Scott Kennedy3c32b622015-02-22 16:58:58 -0800204 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
Dianne Hackborn42c29362010-07-28 14:32:15 -0700205 super.onActivityCreated(savedInstanceState);
Dianne Hackborn42c29362010-07-28 14:32:15 -0700206
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
Amith Yamasanic56fc752011-06-14 15:07:49 -0700225 public void onStart() {
226 super.onStart();
227 mPreferenceManager.setOnPreferenceTreeClickListener(this);
228 }
229
230 @Override
Dianne Hackborn42c29362010-07-28 14:32:15 -0700231 public void onStop() {
232 super.onStop();
233 mPreferenceManager.dispatchActivityStop();
Amith Yamasanic56fc752011-06-14 15:07:49 -0700234 mPreferenceManager.setOnPreferenceTreeClickListener(null);
Dianne Hackborn42c29362010-07-28 14:32:15 -0700235 }
236
237 @Override
Dianne Hackbornb3cf10f2010-08-03 13:07:11 -0700238 public void onDestroyView() {
Mykola Kondratenko5e18c402015-02-09 19:20:28 +0100239 if (mList != null) {
240 mList.setOnKeyListener(null);
241 }
Dianne Hackbornb3cf10f2010-08-03 13:07:11 -0700242 mList = null;
243 mHandler.removeCallbacks(mRequestFocus);
Amith Yamasani81d86002011-03-02 16:11:31 -0800244 mHandler.removeMessages(MSG_BIND_PREFERENCES);
Dianne Hackbornb3cf10f2010-08-03 13:07:11 -0700245 super.onDestroyView();
246 }
247
248 @Override
Dianne Hackborn42c29362010-07-28 14:32:15 -0700249 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) {
Fabrice Di Megliob1a50f22014-08-13 10:41:40 -0700288 onUnbindPreferences();
Dianne Hackborn42c29362010-07-28 14:32:15 -0700289 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 */
Tor Norbye417ee5b2015-03-10 20:57:37 -0700323 public void addPreferencesFromResource(@XmlRes int preferencesResId) {
Dianne Hackborn42c29362010-07-28 14:32:15 -0700324 requirePreferenceManager();
325
326 setPreferenceScreen(mPreferenceManager.inflateFromResource(getActivity(),
327 preferencesResId, getPreferenceScreen()));
328 }
329
330 /**
331 * {@inheritDoc}
332 */
Dianne Hackbornb3cf10f2010-08-03 13:07:11 -0700333 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 }
Dianne Hackborn42c29362010-07-28 14:32:15 -0700340 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 }
Fabrice Di Meglio8a86d732014-04-17 17:14:59 -0700373 onBindPreferences();
374 }
375
376 /** @hide */
377 protected void onBindPreferences() {
Dianne Hackborn42c29362010-07-28 14:32:15 -0700378 }
379
Amith Yamasani9ae5473e2010-08-17 16:49:58 -0700380 /** @hide */
Fabrice Di Megliob1a50f22014-08-13 10:41:40 -0700381 protected void onUnbindPreferences() {
382 }
383
384 /** @hide */
Amith Yamasani9ae5473e2010-08-17 16:49:58 -0700385 public ListView getListView() {
Dianne Hackborn42c29362010-07-28 14:32:15 -0700386 ensureList();
387 return mList;
388 }
389
Fabrice Di Meglio35d7b892014-04-15 19:15:20 -0700390 /** @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
Dianne Hackborn42c29362010-07-28 14:32:15 -0700410 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 }
John Reck014fea22011-06-15 16:46:36 -0700430 mList.setOnKeyListener(mListOnKeyListener);
Dianne Hackborn42c29362010-07-28 14:32:15 -0700431 mHandler.post(mRequestFocus);
432 }
John Reck014fea22011-06-15 16:46:36 -0700433
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 };
Dianne Hackborn42c29362010-07-28 14:32:15 -0700448}