PreferenceActivity.java revision 8eb2e244f9b14d946ee587d0b673b866865026c0
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 findViewById(com.android.internal.R.id.headers).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.getResourceId( 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, Fragment, int)} 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, null, 0); 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 Fragment resultTo, int resultRequestCode) { 857 Intent intent = new Intent(Intent.ACTION_MAIN); 858 intent.setClass(this, getClass()); 859 intent.putExtra(EXTRA_SHOW_FRAGMENT, fragmentName); 860 intent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args); 861 intent.putExtra(EXTRA_NO_HEADERS, true); 862 if (resultTo == null) { 863 startActivity(intent); 864 } else { 865 resultTo.startActivityForResult(intent, resultRequestCode); 866 } 867 } 868 869 /** 870 * Change the base title of the bread crumbs for the current preferences. 871 * This will normally be called for you. See 872 * {@link android.app.FragmentBreadCrumbs} for more information. 873 */ 874 public void showBreadCrumbs(CharSequence title, CharSequence shortTitle) { 875 if (mFragmentBreadCrumbs == null) { 876 mFragmentBreadCrumbs = new FragmentBreadCrumbs(this); 877 mFragmentBreadCrumbs.setActivity(this); 878 getActionBar().setCustomNavigationMode(mFragmentBreadCrumbs); 879 } 880 mFragmentBreadCrumbs.setTitle(title, shortTitle); 881 } 882 883 void setSelectedHeader(Header header) { 884 mCurHeader = header; 885 int index = mHeaders.indexOf(header); 886 if (index >= 0) { 887 getListView().setItemChecked(index, true); 888 } else { 889 getListView().clearChoices(); 890 } 891 if (header != null) { 892 CharSequence title = header.breadCrumbTitle; 893 if (title == null) title = header.title; 894 if (title == null) title = getTitle(); 895 showBreadCrumbs(title, header.breadCrumbShortTitle); 896 } else { 897 showBreadCrumbs(getTitle(), null); 898 } 899 } 900 901 private void switchToHeaderInner(String fragmentName, Bundle args, int direction) { 902 getFragmentManager().popBackStack(BACK_STACK_PREFS, POP_BACK_STACK_INCLUSIVE); 903 Fragment f = Fragment.instantiate(this, fragmentName, args); 904 FragmentTransaction transaction = getFragmentManager().openTransaction(); 905 transaction.setTransition(direction == 0 ? FragmentTransaction.TRANSIT_NONE 906 : direction > 0 ? FragmentTransaction.TRANSIT_FRAGMENT_NEXT 907 : FragmentTransaction.TRANSIT_FRAGMENT_PREV); 908 transaction.replace(com.android.internal.R.id.prefs, f); 909 transaction.commit(); 910 } 911 912 /** 913 * When in two-pane mode, switch the fragment pane to show the given 914 * preference fragment. 915 * 916 * @param fragmentName The name of the fragment to display. 917 * @param args Optional arguments to supply to the fragment. 918 */ 919 public void switchToHeader(String fragmentName, Bundle args) { 920 setSelectedHeader(null); 921 switchToHeaderInner(fragmentName, args, 0); 922 } 923 924 /** 925 * When in two-pane mode, switch to the fragment pane to show the given 926 * preference fragment. 927 * 928 * @param header The new header to display. 929 */ 930 public void switchToHeader(Header header) { 931 if (mCurHeader == header) { 932 // This is the header we are currently displaying. Just make sure 933 // to pop the stack up to its root state. 934 getFragmentManager().popBackStack(BACK_STACK_PREFS, POP_BACK_STACK_INCLUSIVE); 935 } else { 936 int direction = mHeaders.indexOf(header) - mHeaders.indexOf(mCurHeader); 937 switchToHeaderInner(header.fragment, header.fragmentArguments, direction); 938 setSelectedHeader(header); 939 } 940 } 941 942 Header findBestMatchingHeader(Header cur, ArrayList<Header> from) { 943 ArrayList<Header> matches = new ArrayList<Header>(); 944 for (int j=0; j<from.size(); j++) { 945 Header oh = from.get(j); 946 if (cur == oh || (cur.id != HEADER_ID_UNDEFINED && cur.id == oh.id)) { 947 // Must be this one. 948 matches.clear(); 949 matches.add(oh); 950 break; 951 } 952 if (cur.fragment != null) { 953 if (cur.fragment.equals(oh.fragment)) { 954 matches.add(oh); 955 } 956 } else if (cur.intent != null) { 957 if (cur.intent.equals(oh.intent)) { 958 matches.add(oh); 959 } 960 } else if (cur.title != null) { 961 if (cur.title.equals(oh.title)) { 962 matches.add(oh); 963 } 964 } 965 } 966 final int NM = matches.size(); 967 if (NM == 1) { 968 return matches.get(0); 969 } else if (NM > 1) { 970 for (int j=0; j<NM; j++) { 971 Header oh = matches.get(j); 972 if (cur.fragmentArguments != null && 973 cur.fragmentArguments.equals(oh.fragmentArguments)) { 974 return oh; 975 } 976 if (cur.extras != null && cur.extras.equals(oh.extras)) { 977 return oh; 978 } 979 if (cur.title != null && cur.title.equals(oh.title)) { 980 return oh; 981 } 982 } 983 } 984 return null; 985 } 986 987 /** 988 * Start a new fragment. 989 * 990 * @param fragment The fragment to start 991 * @param push If true, the current fragment will be pushed onto the back stack. If false, 992 * the current fragment will be replaced. 993 */ 994 public void startPreferenceFragment(Fragment fragment, boolean push) { 995 FragmentTransaction transaction = getFragmentManager().openTransaction(); 996 transaction.replace(com.android.internal.R.id.prefs, fragment); 997 if (push) { 998 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); 999 transaction.addToBackStack(BACK_STACK_PREFS); 1000 } else { 1001 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_NEXT); 1002 } 1003 transaction.commit(); 1004 } 1005 1006 /** 1007 * Start a new fragment containing a preference panel. If the prefences 1008 * are being displayed in multi-pane mode, the given fragment class will 1009 * be instantiated and placed in the appropriate pane. If running in 1010 * single-pane mode, a new activity will be launched in which to show the 1011 * fragment. 1012 * 1013 * @param fragmentClass Full name of the class implementing the fragment. 1014 * @param args Any desired arguments to supply to the fragment. 1015 * @param titleRes Optional resource identifier of the title of this 1016 * fragment. 1017 * @param titleText Optional text of the title of this fragment. 1018 * @param resultTo Optional fragment that result data should be sent to. 1019 * If non-null, resultTo.onActivityResult() will be called when this 1020 * preference panel is done. The launched panel must use 1021 * {@link #finishPreferencePanel(Fragment, int, Intent)} when done. 1022 * @param resultRequestCode If resultTo is non-null, this is the caller's 1023 * request code to be received with the resut. 1024 */ 1025 public void startPreferencePanel(String fragmentClass, Bundle args, int titleRes, 1026 CharSequence titleText, Fragment resultTo, int resultRequestCode) { 1027 if (mSinglePane) { 1028 startWithFragment(fragmentClass, args, resultTo, resultRequestCode); 1029 } else { 1030 Fragment f = Fragment.instantiate(this, fragmentClass, args); 1031 if (resultTo != null) { 1032 f.setTargetFragment(resultTo, resultRequestCode); 1033 } 1034 FragmentTransaction transaction = getFragmentManager().openTransaction(); 1035 transaction.replace(com.android.internal.R.id.prefs, f); 1036 if (titleRes != 0) { 1037 transaction.setBreadCrumbTitle(titleRes); 1038 } else if (titleText != null) { 1039 transaction.setBreadCrumbTitle(titleText); 1040 } 1041 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); 1042 transaction.addToBackStack(BACK_STACK_PREFS); 1043 transaction.commit(); 1044 } 1045 } 1046 1047 /** 1048 * Called by a preference panel fragment to finish itself. 1049 * 1050 * @param caller The fragment that is asking to be finished. 1051 * @param resultCode Optional result code to send back to the original 1052 * launching fragment. 1053 * @param resultData Optional result data to send back to the original 1054 * launching fragment. 1055 */ 1056 public void finishPreferencePanel(Fragment caller, int resultCode, Intent resultData) { 1057 if (mSinglePane) { 1058 setResult(resultCode, resultData); 1059 finish(); 1060 } else { 1061 if (caller != null) { 1062 if (caller.getTargetFragment() != null) { 1063 caller.getTargetFragment().onActivityResult(caller.getTargetRequestCode(), 1064 resultCode, resultData); 1065 } 1066 } 1067 // XXX be smarter about popping the stack. 1068 onBackPressed(); 1069 } 1070 } 1071 1072 @Override 1073 public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) { 1074 startPreferencePanel(pref.getFragment(), pref.getExtras(), 0, pref.getTitle(), null, 0); 1075 return true; 1076 } 1077 1078 /** 1079 * Posts a message to bind the preferences to the list view. 1080 * <p> 1081 * Binding late is preferred as any custom preference types created in 1082 * {@link #onCreate(Bundle)} are able to have their views recycled. 1083 */ 1084 private void postBindPreferences() { 1085 if (mHandler.hasMessages(MSG_BIND_PREFERENCES)) return; 1086 mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget(); 1087 } 1088 1089 private void bindPreferences() { 1090 final PreferenceScreen preferenceScreen = getPreferenceScreen(); 1091 if (preferenceScreen != null) { 1092 preferenceScreen.bind(getListView()); 1093 if (mSavedInstanceState != null) { 1094 super.onRestoreInstanceState(mSavedInstanceState); 1095 mSavedInstanceState = null; 1096 } 1097 } 1098 } 1099 1100 /** 1101 * Returns the {@link PreferenceManager} used by this activity. 1102 * @return The {@link PreferenceManager}. 1103 * 1104 * @deprecated This function is not relevant for a modern fragment-based 1105 * PreferenceActivity. 1106 */ 1107 @Deprecated 1108 public PreferenceManager getPreferenceManager() { 1109 return mPreferenceManager; 1110 } 1111 1112 private void requirePreferenceManager() { 1113 if (mPreferenceManager == null) { 1114 if (mAdapter == null) { 1115 throw new RuntimeException("This should be called after super.onCreate."); 1116 } 1117 throw new RuntimeException( 1118 "Modern two-pane PreferenceActivity requires use of a PreferenceFragment"); 1119 } 1120 } 1121 1122 /** 1123 * Sets the root of the preference hierarchy that this activity is showing. 1124 * 1125 * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy. 1126 * 1127 * @deprecated This function is not relevant for a modern fragment-based 1128 * PreferenceActivity. 1129 */ 1130 @Deprecated 1131 public void setPreferenceScreen(PreferenceScreen preferenceScreen) { 1132 requirePreferenceManager(); 1133 1134 if (mPreferenceManager.setPreferences(preferenceScreen) && preferenceScreen != null) { 1135 postBindPreferences(); 1136 CharSequence title = getPreferenceScreen().getTitle(); 1137 // Set the title of the activity 1138 if (title != null) { 1139 setTitle(title); 1140 } 1141 } 1142 } 1143 1144 /** 1145 * Gets the root of the preference hierarchy that this activity is showing. 1146 * 1147 * @return The {@link PreferenceScreen} that is the root of the preference 1148 * hierarchy. 1149 * 1150 * @deprecated This function is not relevant for a modern fragment-based 1151 * PreferenceActivity. 1152 */ 1153 @Deprecated 1154 public PreferenceScreen getPreferenceScreen() { 1155 if (mPreferenceManager != null) { 1156 return mPreferenceManager.getPreferenceScreen(); 1157 } 1158 return null; 1159 } 1160 1161 /** 1162 * Adds preferences from activities that match the given {@link Intent}. 1163 * 1164 * @param intent The {@link Intent} to query activities. 1165 * 1166 * @deprecated This function is not relevant for a modern fragment-based 1167 * PreferenceActivity. 1168 */ 1169 @Deprecated 1170 public void addPreferencesFromIntent(Intent intent) { 1171 requirePreferenceManager(); 1172 1173 setPreferenceScreen(mPreferenceManager.inflateFromIntent(intent, getPreferenceScreen())); 1174 } 1175 1176 /** 1177 * Inflates the given XML resource and adds the preference hierarchy to the current 1178 * preference hierarchy. 1179 * 1180 * @param preferencesResId The XML resource ID to inflate. 1181 * 1182 * @deprecated This function is not relevant for a modern fragment-based 1183 * PreferenceActivity. 1184 */ 1185 @Deprecated 1186 public void addPreferencesFromResource(int preferencesResId) { 1187 requirePreferenceManager(); 1188 1189 setPreferenceScreen(mPreferenceManager.inflateFromResource(this, preferencesResId, 1190 getPreferenceScreen())); 1191 } 1192 1193 /** 1194 * {@inheritDoc} 1195 * 1196 * @deprecated This function is not relevant for a modern fragment-based 1197 * PreferenceActivity. 1198 */ 1199 @Deprecated 1200 public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { 1201 return false; 1202 } 1203 1204 /** 1205 * Finds a {@link Preference} based on its key. 1206 * 1207 * @param key The key of the preference to retrieve. 1208 * @return The {@link Preference} with the key, or null. 1209 * @see PreferenceGroup#findPreference(CharSequence) 1210 * 1211 * @deprecated This function is not relevant for a modern fragment-based 1212 * PreferenceActivity. 1213 */ 1214 @Deprecated 1215 public Preference findPreference(CharSequence key) { 1216 1217 if (mPreferenceManager == null) { 1218 return null; 1219 } 1220 1221 return mPreferenceManager.findPreference(key); 1222 } 1223 1224 @Override 1225 protected void onNewIntent(Intent intent) { 1226 if (mPreferenceManager != null) { 1227 mPreferenceManager.dispatchNewIntent(intent); 1228 } 1229 } 1230 1231 // give subclasses access to the Next button 1232 /** @hide */ 1233 protected boolean hasNextButton() { 1234 return mNextButton != null; 1235 } 1236 /** @hide */ 1237 protected Button getNextButton() { 1238 return mNextButton; 1239 } 1240} 1241