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