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