PreferenceActivity.java revision c6669ca63299219d815464129dac051ab2404286
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 mAdapter.notifyDataSetChanged(); 207 Header header = onGetNewHeader(); 208 if (header != null && header.fragment != null) { 209 Header mappedHeader = findBestMatchingHeader(header, oldHeaders); 210 if (mappedHeader == null || mCurHeader != mappedHeader) { 211 switchToHeader(header); 212 } 213 } else if (mCurHeader != null) { 214 Header mappedHeader = findBestMatchingHeader(mCurHeader, mHeaders); 215 if (mappedHeader != null) { 216 setSelectedHeader(mappedHeader); 217 } else { 218 switchToHeader(null); 219 } 220 } 221 } break; 222 } 223 } 224 }; 225 226 private static class HeaderAdapter extends ArrayAdapter<Header> { 227 private static class HeaderViewHolder { 228 ImageView icon; 229 TextView title; 230 TextView summary; 231 } 232 233 private LayoutInflater mInflater; 234 235 public HeaderAdapter(Context context, List<Header> objects) { 236 super(context, 0, objects); 237 mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 238 } 239 240 @Override 241 public View getView(int position, View convertView, ViewGroup parent) { 242 HeaderViewHolder holder; 243 View view; 244 245 if (convertView == null) { 246 view = mInflater.inflate(com.android.internal.R.layout.preference_header_item, 247 parent, false); 248 holder = new HeaderViewHolder(); 249 holder.icon = (ImageView) view.findViewById(com.android.internal.R.id.icon); 250 holder.title = (TextView) view.findViewById(com.android.internal.R.id.title); 251 holder.summary = (TextView) view.findViewById(com.android.internal.R.id.summary); 252 view.setTag(holder); 253 } else { 254 view = convertView; 255 holder = (HeaderViewHolder) view.getTag(); 256 } 257 258 // All view fields must be updated every time, because the view may be recycled 259 Header header = getItem(position); 260 holder.icon.setImageResource(header.iconRes); 261 holder.title.setText(header.title); 262 if (TextUtils.isEmpty(header.summary)) { 263 holder.summary.setVisibility(View.GONE); 264 } else { 265 holder.summary.setVisibility(View.VISIBLE); 266 holder.summary.setText(header.summary); 267 } 268 269 return view; 270 } 271 } 272 273 /** 274 * Default value for {@link Header#id Header.id} indicating that no 275 * identifier value is set. All other values (including those below -1) 276 * are valid. 277 */ 278 public static final long HEADER_ID_UNDEFINED = -1; 279 280 /** 281 * Description of a single Header item that the user can select. 282 */ 283 public static final class Header implements Parcelable { 284 /** 285 * Identifier for this header, to correlate with a new list when 286 * it is updated. The default value is 287 * {@link PreferenceActivity#HEADER_ID_UNDEFINED}, meaning no id. 288 * @attr ref android.R.styleable#PreferenceHeader_id 289 */ 290 public long id = HEADER_ID_UNDEFINED; 291 292 /** 293 * Title of the header that is shown to the user. 294 * @attr ref android.R.styleable#PreferenceHeader_title 295 */ 296 public CharSequence title; 297 298 /** 299 * Optional summary describing what this header controls. 300 * @attr ref android.R.styleable#PreferenceHeader_summary 301 */ 302 public CharSequence summary; 303 304 /** 305 * Optional text to show as the title in the bread crumb. 306 * @attr ref android.R.styleable#PreferenceHeader_breadCrumbTitle 307 */ 308 public CharSequence breadCrumbTitle; 309 310 /** 311 * Optional text to show as the short title in the bread crumb. 312 * @attr ref android.R.styleable#PreferenceHeader_breadCrumbShortTitle 313 */ 314 public CharSequence breadCrumbShortTitle; 315 316 /** 317 * Optional icon resource to show for this header. 318 * @attr ref android.R.styleable#PreferenceHeader_icon 319 */ 320 public int iconRes; 321 322 /** 323 * Full class name of the fragment to display when this header is 324 * selected. 325 * @attr ref android.R.styleable#PreferenceHeader_fragment 326 */ 327 public String fragment; 328 329 /** 330 * Optional arguments to supply to the fragment when it is 331 * instantiated. 332 */ 333 public Bundle fragmentArguments; 334 335 /** 336 * Intent to launch when the preference is selected. 337 */ 338 public Intent intent; 339 340 /** 341 * Optional additional data for use by subclasses of PreferenceActivity. 342 */ 343 public Bundle extras; 344 345 public Header() { 346 } 347 348 @Override 349 public int describeContents() { 350 return 0; 351 } 352 353 @Override 354 public void writeToParcel(Parcel dest, int flags) { 355 dest.writeLong(id); 356 TextUtils.writeToParcel(title, dest, flags); 357 TextUtils.writeToParcel(summary, dest, flags); 358 TextUtils.writeToParcel(breadCrumbTitle, dest, flags); 359 TextUtils.writeToParcel(breadCrumbShortTitle, dest, flags); 360 dest.writeInt(iconRes); 361 dest.writeString(fragment); 362 dest.writeBundle(fragmentArguments); 363 if (intent != null) { 364 dest.writeInt(1); 365 intent.writeToParcel(dest, flags); 366 } else { 367 dest.writeInt(0); 368 } 369 dest.writeBundle(extras); 370 } 371 372 public void readFromParcel(Parcel in) { 373 id = in.readLong(); 374 title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 375 summary = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 376 breadCrumbTitle = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 377 breadCrumbShortTitle = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 378 iconRes = in.readInt(); 379 fragment = in.readString(); 380 fragmentArguments = in.readBundle(); 381 if (in.readInt() != 0) { 382 intent = Intent.CREATOR.createFromParcel(in); 383 } 384 extras = in.readBundle(); 385 } 386 387 Header(Parcel in) { 388 readFromParcel(in); 389 } 390 391 public static final Creator<Header> CREATOR = new Creator<Header>() { 392 public Header createFromParcel(Parcel source) { 393 return new Header(source); 394 } 395 public Header[] newArray(int size) { 396 return new Header[size]; 397 } 398 }; 399 } 400 401 @Override 402 protected void onCreate(Bundle savedInstanceState) { 403 super.onCreate(savedInstanceState); 404 405 setContentView(com.android.internal.R.layout.preference_list_content); 406 407 mListFooter = (FrameLayout)findViewById(com.android.internal.R.id.list_footer); 408 mPrefsContainer = findViewById(com.android.internal.R.id.prefs); 409 boolean hidingHeaders = onIsHidingHeaders(); 410 mSinglePane = hidingHeaders || !onIsMultiPane(); 411 String initialFragment = getIntent().getStringExtra(EXTRA_SHOW_FRAGMENT); 412 Bundle initialArguments = getIntent().getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS); 413 414 if (savedInstanceState != null) { 415 // We are restarting from a previous saved state; used that to 416 // initialize, instead of starting fresh. 417 ArrayList<Header> headers = savedInstanceState.getParcelableArrayList(HEADERS_TAG); 418 if (headers != null) { 419 mHeaders.addAll(headers); 420 int curHeader = savedInstanceState.getInt(CUR_HEADER_TAG, 421 (int)HEADER_ID_UNDEFINED); 422 if (curHeader >= 0 && curHeader < mHeaders.size()) { 423 setSelectedHeader(mHeaders.get(curHeader)); 424 } 425 } 426 427 } else { 428 if (initialFragment != null && mSinglePane) { 429 // If we are just showing a fragment, we want to run in 430 // new fragment mode, but don't need to compute and show 431 // the headers. 432 switchToHeader(initialFragment, initialArguments); 433 434 } else { 435 // We need to try to build the headers. 436 onBuildHeaders(mHeaders); 437 438 // If there are headers, then at this point we need to show 439 // them and, depending on the screen, we may also show in-line 440 // the currently selected preference fragment. 441 if (mHeaders.size() > 0) { 442 if (!mSinglePane) { 443 if (initialFragment == null) { 444 Header h = onGetInitialHeader(); 445 switchToHeader(h); 446 } else { 447 switchToHeader(initialFragment, initialArguments); 448 } 449 } 450 } 451 } 452 } 453 454 // The default configuration is to only show the list view. Adjust 455 // visibility for other configurations. 456 if (initialFragment != null && mSinglePane) { 457 // Single pane, showing just a prefs fragment. 458 getListView().setVisibility(View.GONE); 459 mPrefsContainer.setVisibility(View.VISIBLE); 460 } else if (mHeaders.size() > 0) { 461 mAdapter = new HeaderAdapter(this, mHeaders); 462 setListAdapter(mAdapter); 463 if (!mSinglePane) { 464 // Multi-pane. 465 getListView().setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); 466 if (mCurHeader != null) { 467 setSelectedHeader(mCurHeader); 468 } 469 mPrefsContainer.setVisibility(View.VISIBLE); 470 } 471 } else { 472 // If there are no headers, we are in the old "just show a screen 473 // of preferences" mode. 474 mPreferenceManager = new PreferenceManager(this, FIRST_REQUEST_CODE); 475 mPreferenceManager.setOnPreferenceTreeClickListener(this); 476 } 477 478 getListView().setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); 479 480 // see if we should show Back/Next buttons 481 Intent intent = getIntent(); 482 if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_BUTTON_BAR, false)) { 483 484 findViewById(com.android.internal.R.id.button_bar).setVisibility(View.VISIBLE); 485 486 Button backButton = (Button)findViewById(com.android.internal.R.id.back_button); 487 backButton.setOnClickListener(new OnClickListener() { 488 public void onClick(View v) { 489 setResult(RESULT_CANCELED); 490 finish(); 491 } 492 }); 493 Button skipButton = (Button)findViewById(com.android.internal.R.id.skip_button); 494 skipButton.setOnClickListener(new OnClickListener() { 495 public void onClick(View v) { 496 setResult(RESULT_OK); 497 finish(); 498 } 499 }); 500 mNextButton = (Button)findViewById(com.android.internal.R.id.next_button); 501 mNextButton.setOnClickListener(new OnClickListener() { 502 public void onClick(View v) { 503 setResult(RESULT_OK); 504 finish(); 505 } 506 }); 507 508 // set our various button parameters 509 if (intent.hasExtra(EXTRA_PREFS_SET_NEXT_TEXT)) { 510 String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_NEXT_TEXT); 511 if (TextUtils.isEmpty(buttonText)) { 512 mNextButton.setVisibility(View.GONE); 513 } 514 else { 515 mNextButton.setText(buttonText); 516 } 517 } 518 if (intent.hasExtra(EXTRA_PREFS_SET_BACK_TEXT)) { 519 String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_BACK_TEXT); 520 if (TextUtils.isEmpty(buttonText)) { 521 backButton.setVisibility(View.GONE); 522 } 523 else { 524 backButton.setText(buttonText); 525 } 526 } 527 if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_SKIP, false)) { 528 skipButton.setVisibility(View.VISIBLE); 529 } 530 } 531 } 532 533 /** 534 * Returns true if this activity is currently showing the header list. 535 */ 536 public boolean hasHeaders() { 537 return getListView().getVisibility() == View.VISIBLE 538 && mPreferenceManager == null; 539 } 540 541 /** 542 * Returns true if this activity is showing multiple panes -- the headers 543 * and a preference fragment. 544 */ 545 public boolean isMultiPane() { 546 return hasHeaders() && mPrefsContainer.getVisibility() == View.VISIBLE; 547 } 548 549 /** 550 * Called to determine if the activity should run in multi-pane mode. 551 * The default implementation returns true if the screen is large 552 * enough. 553 */ 554 public boolean onIsMultiPane() { 555 Configuration config = getResources().getConfiguration(); 556 if ((config.screenLayout&Configuration.SCREENLAYOUT_SIZE_MASK) 557 == Configuration.SCREENLAYOUT_SIZE_XLARGE) { 558 return true; 559 } 560 if ((config.screenLayout&Configuration.SCREENLAYOUT_SIZE_MASK) 561 == Configuration.SCREENLAYOUT_SIZE_LARGE 562 && config.orientation == Configuration.ORIENTATION_LANDSCAPE) { 563 return true; 564 } 565 return false; 566 } 567 568 /** 569 * Called to determine whether the header list should be hidden. 570 * The default implementation returns the 571 * value given in {@link #EXTRA_NO_HEADERS} or false if it is not supplied. 572 * This is set to false, for example, when the activity is being re-launched 573 * to show a particular preference activity. 574 */ 575 public boolean onIsHidingHeaders() { 576 return getIntent().getBooleanExtra(EXTRA_NO_HEADERS, false); 577 } 578 579 /** 580 * Called to determine the initial header to be shown. The default 581 * implementation simply returns the fragment of the first header. Note 582 * that the returned Header object does not actually need to exist in 583 * your header list -- whatever its fragment is will simply be used to 584 * show for the initial UI. 585 */ 586 public Header onGetInitialHeader() { 587 return mHeaders.get(0); 588 } 589 590 /** 591 * Called after the header list has been updated ({@link #onBuildHeaders} 592 * has been called and returned due to {@link #invalidateHeaders()}) to 593 * specify the header that should now be selected. The default implementation 594 * returns null to keep whatever header is currently selected. 595 */ 596 public Header onGetNewHeader() { 597 return null; 598 } 599 600 /** 601 * Called when the activity needs its list of headers build. By 602 * implementing this and adding at least one item to the list, you 603 * will cause the activity to run in its modern fragment mode. Note 604 * that this function may not always be called; for example, if the 605 * activity has been asked to display a particular fragment without 606 * the header list, there is no need to build the headers. 607 * 608 * <p>Typical implementations will use {@link #loadHeadersFromResource} 609 * to fill in the list from a resource. 610 * 611 * @param target The list in which to place the headers. 612 */ 613 public void onBuildHeaders(List<Header> target) { 614 } 615 616 /** 617 * Call when you need to change the headers being displayed. Will result 618 * in onBuildHeaders() later being called to retrieve the new list. 619 */ 620 public void invalidateHeaders() { 621 if (!mHandler.hasMessages(MSG_BUILD_HEADERS)) { 622 mHandler.sendEmptyMessage(MSG_BUILD_HEADERS); 623 } 624 } 625 626 /** 627 * Parse the given XML file as a header description, adding each 628 * parsed Header into the target list. 629 * 630 * @param resid The XML resource to load and parse. 631 * @param target The list in which the parsed headers should be placed. 632 */ 633 public void loadHeadersFromResource(int resid, List<Header> target) { 634 XmlResourceParser parser = null; 635 try { 636 parser = getResources().getXml(resid); 637 AttributeSet attrs = Xml.asAttributeSet(parser); 638 639 int type; 640 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 641 && type != XmlPullParser.START_TAG) { 642 } 643 644 String nodeName = parser.getName(); 645 if (!"preference-headers".equals(nodeName)) { 646 throw new RuntimeException( 647 "XML document must start with <preference-headers> tag; found" 648 + nodeName + " at " + parser.getPositionDescription()); 649 } 650 651 Bundle curBundle = null; 652 653 final int outerDepth = parser.getDepth(); 654 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 655 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 656 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 657 continue; 658 } 659 660 nodeName = parser.getName(); 661 if ("header".equals(nodeName)) { 662 Header header = new Header(); 663 664 TypedArray sa = getResources().obtainAttributes(attrs, 665 com.android.internal.R.styleable.PreferenceHeader); 666 header.id = sa.getInt( 667 com.android.internal.R.styleable.PreferenceHeader_id, 668 (int)HEADER_ID_UNDEFINED); 669 header.title = sa.getText( 670 com.android.internal.R.styleable.PreferenceHeader_title); 671 header.summary = sa.getText( 672 com.android.internal.R.styleable.PreferenceHeader_summary); 673 header.breadCrumbTitle = sa.getText( 674 com.android.internal.R.styleable.PreferenceHeader_breadCrumbTitle); 675 header.breadCrumbShortTitle = sa.getText( 676 com.android.internal.R.styleable.PreferenceHeader_breadCrumbShortTitle); 677 header.iconRes = sa.getResourceId( 678 com.android.internal.R.styleable.PreferenceHeader_icon, 0); 679 header.fragment = sa.getString( 680 com.android.internal.R.styleable.PreferenceHeader_fragment); 681 sa.recycle(); 682 683 if (curBundle == null) { 684 curBundle = new Bundle(); 685 } 686 687 final int innerDepth = parser.getDepth(); 688 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 689 && (type != XmlPullParser.END_TAG || parser.getDepth() > innerDepth)) { 690 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 691 continue; 692 } 693 694 String innerNodeName = parser.getName(); 695 if (innerNodeName.equals("extra")) { 696 getResources().parseBundleExtra("extra", attrs, curBundle); 697 XmlUtils.skipCurrentTag(parser); 698 699 } else if (innerNodeName.equals("intent")) { 700 header.intent = Intent.parseIntent(getResources(), parser, attrs); 701 702 } else { 703 XmlUtils.skipCurrentTag(parser); 704 } 705 } 706 707 if (curBundle.size() > 0) { 708 header.fragmentArguments = curBundle; 709 curBundle = null; 710 } 711 712 target.add(header); 713 } else { 714 XmlUtils.skipCurrentTag(parser); 715 } 716 } 717 718 } catch (XmlPullParserException e) { 719 throw new RuntimeException("Error parsing headers", e); 720 } catch (IOException e) { 721 throw new RuntimeException("Error parsing headers", e); 722 } finally { 723 if (parser != null) parser.close(); 724 } 725 726 } 727 728 /** 729 * Set a footer that should be shown at the bottom of the header list. 730 */ 731 public void setListFooter(View view) { 732 mListFooter.removeAllViews(); 733 mListFooter.addView(view, new FrameLayout.LayoutParams( 734 FrameLayout.LayoutParams.MATCH_PARENT, 735 FrameLayout.LayoutParams.WRAP_CONTENT)); 736 } 737 738 @Override 739 protected void onStop() { 740 super.onStop(); 741 742 if (mPreferenceManager != null) { 743 mPreferenceManager.dispatchActivityStop(); 744 } 745 } 746 747 @Override 748 protected void onDestroy() { 749 super.onDestroy(); 750 751 if (mPreferenceManager != null) { 752 mPreferenceManager.dispatchActivityDestroy(); 753 } 754 } 755 756 @Override 757 protected void onSaveInstanceState(Bundle outState) { 758 super.onSaveInstanceState(outState); 759 760 if (mHeaders.size() > 0) { 761 outState.putParcelableArrayList(HEADERS_TAG, mHeaders); 762 if (mCurHeader != null) { 763 int index = mHeaders.indexOf(mCurHeader); 764 if (index >= 0) { 765 outState.putInt(CUR_HEADER_TAG, index); 766 } 767 } 768 } 769 770 if (mPreferenceManager != null) { 771 final PreferenceScreen preferenceScreen = getPreferenceScreen(); 772 if (preferenceScreen != null) { 773 Bundle container = new Bundle(); 774 preferenceScreen.saveHierarchyState(container); 775 outState.putBundle(PREFERENCES_TAG, container); 776 } 777 } 778 } 779 780 @Override 781 protected void onRestoreInstanceState(Bundle state) { 782 if (mPreferenceManager != null) { 783 Bundle container = state.getBundle(PREFERENCES_TAG); 784 if (container != null) { 785 final PreferenceScreen preferenceScreen = getPreferenceScreen(); 786 if (preferenceScreen != null) { 787 preferenceScreen.restoreHierarchyState(container); 788 mSavedInstanceState = state; 789 return; 790 } 791 } 792 } 793 794 // Only call this if we didn't save the instance state for later. 795 // If we did save it, it will be restored when we bind the adapter. 796 super.onRestoreInstanceState(state); 797 } 798 799 @Override 800 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 801 super.onActivityResult(requestCode, resultCode, data); 802 803 if (mPreferenceManager != null) { 804 mPreferenceManager.dispatchActivityResult(requestCode, resultCode, data); 805 } 806 } 807 808 @Override 809 public void onContentChanged() { 810 super.onContentChanged(); 811 812 if (mPreferenceManager != null) { 813 postBindPreferences(); 814 } 815 } 816 817 @Override 818 protected void onListItemClick(ListView l, View v, int position, long id) { 819 super.onListItemClick(l, v, position, id); 820 821 if (mAdapter != null) { 822 onHeaderClick(mHeaders.get(position), position); 823 } 824 } 825 826 /** 827 * Called when the user selects an item in the header list. The default 828 * implementation will call either {@link #startWithFragment(String, Bundle)} 829 * or {@link #switchToHeader(Header)} as appropriate. 830 * 831 * @param header The header that was selected. 832 * @param position The header's position in the list. 833 */ 834 public void onHeaderClick(Header header, int position) { 835 if (header.fragment != null) { 836 if (mSinglePane) { 837 startWithFragment(header.fragment, header.fragmentArguments); 838 } else { 839 switchToHeader(header); 840 } 841 } else if (header.intent != null) { 842 startActivity(header.intent); 843 } 844 } 845 846 /** 847 * Start a new instance of this activity, showing only the given 848 * preference fragment. When launched in this mode, the header list 849 * will be hidden and the given preference fragment will be instantiated 850 * and fill the entire activity. 851 * 852 * @param fragmentName The name of the fragment to display. 853 * @param args Optional arguments to supply to the fragment. 854 */ 855 public void startWithFragment(String fragmentName, Bundle args) { 856 Intent intent = new Intent(Intent.ACTION_MAIN); 857 intent.setClass(this, getClass()); 858 intent.putExtra(EXTRA_SHOW_FRAGMENT, fragmentName); 859 intent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args); 860 intent.putExtra(EXTRA_NO_HEADERS, true); 861 startActivity(intent); 862 } 863 864 /** 865 * Change the base title of the bread crumbs for the current preferences. 866 * This will normally be called for you. See 867 * {@link android.app.FragmentBreadCrumbs} for more information. 868 */ 869 public void showBreadCrumbs(CharSequence title, CharSequence shortTitle) { 870 if (mFragmentBreadCrumbs == null) { 871 mFragmentBreadCrumbs = new FragmentBreadCrumbs(this); 872 mFragmentBreadCrumbs.setActivity(this); 873 getActionBar().setCustomNavigationMode(mFragmentBreadCrumbs); 874 } 875 mFragmentBreadCrumbs.setTitle(title, shortTitle); 876 } 877 878 void setSelectedHeader(Header header) { 879 mCurHeader = header; 880 int index = mHeaders.indexOf(header); 881 if (index >= 0) { 882 getListView().setItemChecked(index, true); 883 } else { 884 getListView().clearChoices(); 885 } 886 if (header != null) { 887 CharSequence title = header.breadCrumbTitle; 888 if (title == null) title = header.title; 889 if (title == null) title = getTitle(); 890 showBreadCrumbs(title, header.breadCrumbShortTitle); 891 } else { 892 showBreadCrumbs(getTitle(), null); 893 } 894 } 895 896 public void switchToHeaderInner(String fragmentName, Bundle args) { 897 getFragmentManager().popBackStack(BACK_STACK_PREFS, POP_BACK_STACK_INCLUSIVE); 898 Fragment f = Fragment.instantiate(this, fragmentName, args); 899 getFragmentManager().openTransaction().replace( 900 com.android.internal.R.id.prefs, f).commit(); 901 } 902 903 /** 904 * When in two-pane mode, switch the fragment pane to show the given 905 * preference fragment. 906 * 907 * @param fragmentName The name of the fragment to display. 908 * @param args Optional arguments to supply to the fragment. 909 */ 910 public void switchToHeader(String fragmentName, Bundle args) { 911 setSelectedHeader(null); 912 switchToHeaderInner(fragmentName, args); 913 } 914 915 /** 916 * When in two-pane mode, switch to the fragment pane to show the given 917 * preference fragment. 918 * 919 * @param header The new header to display. 920 */ 921 public void switchToHeader(Header header) { 922 switchToHeaderInner(header.fragment, header.fragmentArguments); 923 setSelectedHeader(header); 924 } 925 926 Header findBestMatchingHeader(Header cur, ArrayList<Header> from) { 927 ArrayList<Header> matches = new ArrayList<Header>(); 928 for (int j=0; j<from.size(); j++) { 929 Header oh = from.get(j); 930 if (cur == oh || (cur.id != HEADER_ID_UNDEFINED && cur.id == oh.id)) { 931 // Must be this one. 932 matches.clear(); 933 matches.add(oh); 934 break; 935 } 936 if (cur.fragment != null) { 937 if (cur.fragment.equals(oh.fragment)) { 938 matches.add(oh); 939 } 940 } else if (cur.intent != null) { 941 if (cur.intent.equals(oh.intent)) { 942 matches.add(oh); 943 } 944 } else if (cur.title != null) { 945 if (cur.title.equals(oh.title)) { 946 matches.add(oh); 947 } 948 } 949 } 950 final int NM = matches.size(); 951 if (NM == 1) { 952 return matches.get(0); 953 } else if (NM > 1) { 954 for (int j=0; j<NM; j++) { 955 Header oh = matches.get(j); 956 if (cur.fragmentArguments != null && 957 cur.fragmentArguments.equals(oh.fragmentArguments)) { 958 return oh; 959 } 960 if (cur.extras != null && cur.extras.equals(oh.extras)) { 961 return oh; 962 } 963 if (cur.title != null && cur.title.equals(oh.title)) { 964 return oh; 965 } 966 } 967 } 968 return null; 969 } 970 971 /** 972 * Start a new fragment. 973 * 974 * @param fragment The fragment to start 975 * @param push If true, the current fragment will be pushed onto the back stack. If false, 976 * the current fragment will be replaced. 977 */ 978 public void startPreferenceFragment(Fragment fragment, boolean push) { 979 FragmentTransaction transaction = getFragmentManager().openTransaction(); 980 startPreferenceFragment(fragment, transaction); 981 if (push) { 982 transaction.addToBackStack(BACK_STACK_PREFS); 983 } 984 transaction.commit(); 985 } 986 987 /** 988 * Start a new fragment. 989 * 990 * @param fragment The fragment to start 991 * @param ft The FragmentTransaction in which to perform this operation. 992 * Will not be added to the back stack or committed for you; you use do that. 993 */ 994 public void startPreferenceFragment(Fragment fragment, FragmentTransaction ft) { 995 ft.replace(com.android.internal.R.id.prefs, fragment); 996 } 997 998 @Override 999 public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) { 1000 Fragment f = Fragment.instantiate(this, pref.getFragment(), pref.getExtras()); 1001 FragmentTransaction transaction = getFragmentManager().openTransaction(); 1002 startPreferenceFragment(f, transaction); 1003 transaction.setBreadCrumbTitle(pref.getTitle()); 1004 transaction.addToBackStack(BACK_STACK_PREFS); 1005 transaction.commit(); 1006 return true; 1007 } 1008 1009 /** 1010 * Posts a message to bind the preferences to the list view. 1011 * <p> 1012 * Binding late is preferred as any custom preference types created in 1013 * {@link #onCreate(Bundle)} are able to have their views recycled. 1014 */ 1015 private void postBindPreferences() { 1016 if (mHandler.hasMessages(MSG_BIND_PREFERENCES)) return; 1017 mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget(); 1018 } 1019 1020 private void bindPreferences() { 1021 final PreferenceScreen preferenceScreen = getPreferenceScreen(); 1022 if (preferenceScreen != null) { 1023 preferenceScreen.bind(getListView()); 1024 if (mSavedInstanceState != null) { 1025 super.onRestoreInstanceState(mSavedInstanceState); 1026 mSavedInstanceState = null; 1027 } 1028 } 1029 } 1030 1031 /** 1032 * Returns the {@link PreferenceManager} used by this activity. 1033 * @return The {@link PreferenceManager}. 1034 * 1035 * @deprecated This function is not relevant for a modern fragment-based 1036 * PreferenceActivity. 1037 */ 1038 @Deprecated 1039 public PreferenceManager getPreferenceManager() { 1040 return mPreferenceManager; 1041 } 1042 1043 private void requirePreferenceManager() { 1044 if (mPreferenceManager == null) { 1045 if (mAdapter == null) { 1046 throw new RuntimeException("This should be called after super.onCreate."); 1047 } 1048 throw new RuntimeException( 1049 "Modern two-pane PreferenceActivity requires use of a PreferenceFragment"); 1050 } 1051 } 1052 1053 /** 1054 * Sets the root of the preference hierarchy that this activity is showing. 1055 * 1056 * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy. 1057 * 1058 * @deprecated This function is not relevant for a modern fragment-based 1059 * PreferenceActivity. 1060 */ 1061 @Deprecated 1062 public void setPreferenceScreen(PreferenceScreen preferenceScreen) { 1063 requirePreferenceManager(); 1064 1065 if (mPreferenceManager.setPreferences(preferenceScreen) && preferenceScreen != null) { 1066 postBindPreferences(); 1067 CharSequence title = getPreferenceScreen().getTitle(); 1068 // Set the title of the activity 1069 if (title != null) { 1070 setTitle(title); 1071 } 1072 } 1073 } 1074 1075 /** 1076 * Gets the root of the preference hierarchy that this activity is showing. 1077 * 1078 * @return The {@link PreferenceScreen} that is the root of the preference 1079 * hierarchy. 1080 * 1081 * @deprecated This function is not relevant for a modern fragment-based 1082 * PreferenceActivity. 1083 */ 1084 @Deprecated 1085 public PreferenceScreen getPreferenceScreen() { 1086 if (mPreferenceManager != null) { 1087 return mPreferenceManager.getPreferenceScreen(); 1088 } 1089 return null; 1090 } 1091 1092 /** 1093 * Adds preferences from activities that match the given {@link Intent}. 1094 * 1095 * @param intent The {@link Intent} to query activities. 1096 * 1097 * @deprecated This function is not relevant for a modern fragment-based 1098 * PreferenceActivity. 1099 */ 1100 @Deprecated 1101 public void addPreferencesFromIntent(Intent intent) { 1102 requirePreferenceManager(); 1103 1104 setPreferenceScreen(mPreferenceManager.inflateFromIntent(intent, getPreferenceScreen())); 1105 } 1106 1107 /** 1108 * Inflates the given XML resource and adds the preference hierarchy to the current 1109 * preference hierarchy. 1110 * 1111 * @param preferencesResId The XML resource ID to inflate. 1112 * 1113 * @deprecated This function is not relevant for a modern fragment-based 1114 * PreferenceActivity. 1115 */ 1116 @Deprecated 1117 public void addPreferencesFromResource(int preferencesResId) { 1118 requirePreferenceManager(); 1119 1120 setPreferenceScreen(mPreferenceManager.inflateFromResource(this, preferencesResId, 1121 getPreferenceScreen())); 1122 } 1123 1124 /** 1125 * {@inheritDoc} 1126 * 1127 * @deprecated This function is not relevant for a modern fragment-based 1128 * PreferenceActivity. 1129 */ 1130 @Deprecated 1131 public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { 1132 return false; 1133 } 1134 1135 /** 1136 * Finds a {@link Preference} based on its key. 1137 * 1138 * @param key The key of the preference to retrieve. 1139 * @return The {@link Preference} with the key, or null. 1140 * @see PreferenceGroup#findPreference(CharSequence) 1141 * 1142 * @deprecated This function is not relevant for a modern fragment-based 1143 * PreferenceActivity. 1144 */ 1145 @Deprecated 1146 public Preference findPreference(CharSequence key) { 1147 1148 if (mPreferenceManager == null) { 1149 return null; 1150 } 1151 1152 return mPreferenceManager.findPreference(key); 1153 } 1154 1155 @Override 1156 protected void onNewIntent(Intent intent) { 1157 if (mPreferenceManager != null) { 1158 mPreferenceManager.dispatchNewIntent(intent); 1159 } 1160 } 1161 1162 // give subclasses access to the Next button 1163 /** @hide */ 1164 protected boolean hasNextButton() { 1165 return mNextButton != null; 1166 } 1167 /** @hide */ 1168 protected Button getNextButton() { 1169 return mNextButton; 1170 } 1171} 1172