1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.preference;
import android.animation.LayoutTransition;
import android.annotation.Nullable;
import android.annotation.StringRes;
import android.annotation.UnsupportedAppUsage;
import android.annotation.XmlRes;
import android.app.Fragment;
import android.app.FragmentBreadCrumbs;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.internal.util.XmlUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* This is the base class for an activity to show a hierarchy of preferences
* to the user. Prior to {@link android.os.Build.VERSION_CODES#HONEYCOMB}
* this class only allowed the display of a single set of preference; this
* functionality should now be found in the new {@link PreferenceFragment}
* class. If you are using PreferenceActivity in its old mode, the documentation
* there applies to the deprecated APIs here.
*
* <p>This activity shows one or more headers of preferences, each of which
* is associated with a {@link PreferenceFragment} to display the preferences
* of that header. The actual layout and display of these associations can
* however vary; currently there are two major approaches it may take:
*
* <ul>
* <li>On a small screen it may display only the headers as a single list when first launched.
* Selecting one of the header items will only show the PreferenceFragment of that header (on
* Android N and lower a new Activity is launched).
* <li>On a large screen it may display both the headers and current PreferenceFragment together as
* panes. Selecting a header item switches to showing the correct PreferenceFragment for that item.
* </ul>
*
* <p>Subclasses of PreferenceActivity should implement
* {@link #onBuildHeaders} to populate the header list with the desired
* items. Doing this implicitly switches the class into its new "headers
* + fragments" mode rather than the old style of just showing a single
* preferences list.
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For information about using {@code PreferenceActivity},
* read the <a href="{@docRoot}guide/topics/ui/settings.html">Settings</a>
* guide.</p>
* </div>
*
* @deprecated Use the <a href="{@docRoot}jetpack/androidx.html">AndroidX</a>
* <a href="{@docRoot}reference/androidx/preference/package-summary.html">
* Preference Library</a> for consistent behavior across all devices. For more information on
* using the AndroidX Preference Library see
* <a href="{@docRoot}guide/topics/ui/settings.html">Settings</a>.
*/
@Deprecated
public abstract class PreferenceActivity extends ListActivity implements
PreferenceManager.OnPreferenceTreeClickListener,
PreferenceFragment.OnPreferenceStartFragmentCallback {
private static final String TAG = "PreferenceActivity";
// Constants for state save/restore
private static final String HEADERS_TAG = ":android:headers";
private static final String CUR_HEADER_TAG = ":android:cur_header";
private static final String PREFERENCES_TAG = ":android:preferences";
/**
* When starting this activity, the invoking Intent can contain this extra
* string to specify which fragment should be initially displayed.
* <p/>Starting from Key Lime Pie, when this argument is passed in, the PreferenceActivity
* will call isValidFragment() to confirm that the fragment class name is valid for this
* activity.
*/
public static final String EXTRA_SHOW_FRAGMENT = ":android:show_fragment";
/**
* When starting this activity and using {@link #EXTRA_SHOW_FRAGMENT},
* this extra can also be specified to supply a Bundle of arguments to pass
* to that fragment when it is instantiated during the initial creation
* of PreferenceActivity.
*/
public static final String EXTRA_SHOW_FRAGMENT_ARGUMENTS = ":android:show_fragment_args";
/**
* When starting this activity and using {@link #EXTRA_SHOW_FRAGMENT},
* this extra can also be specify to supply the title to be shown for
* that fragment.
*/
public static final String EXTRA_SHOW_FRAGMENT_TITLE = ":android:show_fragment_title";
/**
* When starting this activity and using {@link #EXTRA_SHOW_FRAGMENT},
* this extra can also be specify to supply the short title to be shown for
* that fragment.
*/
public static final String EXTRA_SHOW_FRAGMENT_SHORT_TITLE
= ":android:show_fragment_short_title";
/**
* When starting this activity, the invoking Intent can contain this extra
* boolean that the header list should not be displayed. This is most often
* used in conjunction with {@link #EXTRA_SHOW_FRAGMENT} to launch
* the activity to display a specific fragment that the user has navigated
* to.
*/
public static final String EXTRA_NO_HEADERS = ":android:no_headers";
private static final String BACK_STACK_PREFS = ":android:prefs";
// extras that allow any preference activity to be launched as part of a wizard
// show Back and Next buttons? takes boolean parameter
// Back will then return RESULT_CANCELED and Next RESULT_OK
private static final String EXTRA_PREFS_SHOW_BUTTON_BAR = "extra_prefs_show_button_bar";
// add a Skip button?
private static final String EXTRA_PREFS_SHOW_SKIP = "extra_prefs_show_skip";
// specify custom text for the Back or Next buttons, or cause a button to not appear
// at all by setting it to null
private static final String EXTRA_PREFS_SET_NEXT_TEXT = "extra_prefs_set_next_text";
private static final String EXTRA_PREFS_SET_BACK_TEXT = "extra_prefs_set_back_text";
// --- State for new mode when showing a list of headers + prefs fragment
private final ArrayList<Header> mHeaders = new ArrayList<Header>();
private FrameLayout mListFooter;
@UnsupportedAppUsage
private ViewGroup mPrefsContainer;
// Backup of the original activity title. This is used when navigating back to the headers list
// in onBackPress to restore the title.
private CharSequence mActivityTitle;
// Null if in legacy mode.
private ViewGroup mHeadersContainer;
private FragmentBreadCrumbs mFragmentBreadCrumbs;
private boolean mSinglePane;
private Header mCurHeader;
// --- State for old mode when showing a single preference list
@UnsupportedAppUsage
private PreferenceManager mPreferenceManager;
private Bundle mSavedInstanceState;
// --- Common state
private Button mNextButton;
private int mPreferenceHeaderItemResId = 0;
private boolean mPreferenceHeaderRemoveEmptyIcon = false;
/**
* The starting request code given out to preference framework.
*/
private static final int FIRST_REQUEST_CODE = 100;
private static final int MSG_BIND_PREFERENCES = 1;
private static final int MSG_BUILD_HEADERS = 2;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_BIND_PREFERENCES: {
bindPreferences();
} break;
case MSG_BUILD_HEADERS: {
ArrayList<Header> oldHeaders = new ArrayList<Header>(mHeaders);
mHeaders.clear();
onBuildHeaders(mHeaders);
if (mAdapter instanceof BaseAdapter) {
((BaseAdapter) mAdapter).notifyDataSetChanged();
}
Header header = onGetNewHeader();
if (header != null && header.fragment != null) {
Header mappedHeader = findBestMatchingHeader(header, oldHeaders);
if (mappedHeader == null || mCurHeader != mappedHeader) {
switchToHeader(header);
}
} else if (mCurHeader != null) {
Header mappedHeader = findBestMatchingHeader(mCurHeader, mHeaders);
if (mappedHeader != null) {
setSelectedHeader(mappedHeader);
}
}
} break;
}
}
};
private static class HeaderAdapter extends ArrayAdapter<Header> {
private static class HeaderViewHolder {
ImageView icon;
TextView title;
TextView summary;
}
private LayoutInflater mInflater;
private int mLayoutResId;
private boolean mRemoveIconIfEmpty;
public HeaderAdapter(Context context, List<Header> objects, int layoutResId,
boolean removeIconBehavior) {
super(context, 0, objects);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mLayoutResId = layoutResId;
mRemoveIconIfEmpty = removeIconBehavior;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HeaderViewHolder holder;
View view;
if (convertView == null) {
view = mInflater.inflate(mLayoutResId, parent, false);
holder = new HeaderViewHolder();
holder.icon = (ImageView) view.findViewById(com.android.internal.R.id.icon);
holder.title = (TextView) view.findViewById(com.android.internal.R.id.title);
holder.summary = (TextView) view.findViewById(com.android.internal.R.id.summary);
view.setTag(holder);
} else {
view = convertView;
holder = (HeaderViewHolder) view.getTag();
}
// All view fields must be updated every time, because the view may be recycled
Header header = getItem(position);
if (mRemoveIconIfEmpty) {
if (header.iconRes == 0) {
holder.icon.setVisibility(View.GONE);
} else {
holder.icon.setVisibility(View.VISIBLE);
holder.icon.setImageResource(header.iconRes);
}
} else {
holder.icon.setImageResource(header.iconRes);
}
holder.title.setText(header.getTitle(getContext().getResources()));
CharSequence summary = header.getSummary(getContext().getResources());
if (!TextUtils.isEmpty(summary)) {
holder.summary.setVisibility(View.VISIBLE);
holder.summary.setText(summary);
} else {
holder.summary.setVisibility(View.GONE);
}
return view;
}
}
/**
* Default value for {@link Header#id Header.id} indicating that no
* identifier value is set. All other values (including those below -1)
* are valid.
*/
public static final long HEADER_ID_UNDEFINED = -1;
/**
* Description of a single Header item that the user can select.
*
* @deprecated Use the <a href="{@docRoot}jetpack/androidx.html">AndroidX</a>
* <a href="{@docRoot}reference/androidx/preference/package-summary.html">
* Preference Library</a> for consistent behavior across all devices.
* For more information on using the AndroidX Preference Library see
* <a href="{@docRoot}guide/topics/ui/settings.html">Settings</a>.
*/
@Deprecated
public static final class Header implements Parcelable {
/**
* Identifier for this header, to correlate with a new list when
* it is updated. The default value is
* {@link PreferenceActivity#HEADER_ID_UNDEFINED}, meaning no id.
* @attr ref android.R.styleable#PreferenceHeader_id
*/
public long id = HEADER_ID_UNDEFINED;
/**
* Resource ID of title of the header that is shown to the user.
* @attr ref android.R.styleable#PreferenceHeader_title
*/
@StringRes
public int titleRes;
/**
* Title of the header that is shown to the user.
* @attr ref android.R.styleable#PreferenceHeader_title
*/
public CharSequence title;
/**
* Resource ID of optional summary describing what this header controls.
* @attr ref android.R.styleable#PreferenceHeader_summary
*/
@StringRes
public int summaryRes;
/**
* Optional summary describing what this header controls.
* @attr ref android.R.styleable#PreferenceHeader_summary
*/
public CharSequence summary;
/**
* Resource ID of optional text to show as the title in the bread crumb.
* @attr ref android.R.styleable#PreferenceHeader_breadCrumbTitle
*/
@StringRes
public int breadCrumbTitleRes;
/**
* Optional text to show as the title in the bread crumb.
* @attr ref android.R.styleable#PreferenceHeader_breadCrumbTitle
*/
public CharSequence breadCrumbTitle;
/**
* Resource ID of optional text to show as the short title in the bread crumb.
* @attr ref android.R.styleable#PreferenceHeader_breadCrumbShortTitle
*/
@StringRes
public int breadCrumbShortTitleRes;
/**
* Optional text to show as the short title in the bread crumb.
* @attr ref android.R.styleable#PreferenceHeader_breadCrumbShortTitle
*/
public CharSequence breadCrumbShortTitle;
/**
* Optional icon resource to show for this header.
* @attr ref android.R.styleable#PreferenceHeader_icon
*/
public int iconRes;
/**
* Full class name of the fragment to display when this header is
* selected.
* @attr ref android.R.styleable#PreferenceHeader_fragment
*/
public String fragment;
/**
* Optional arguments to supply to the fragment when it is
* instantiated.
*/
public Bundle fragmentArguments;
/**
* Intent to launch when the preference is selected.
*/
public Intent intent;
/**
* Optional additional data for use by subclasses of PreferenceActivity.
*/
public Bundle extras;
public Header() {
// Empty
}
/**
* Return the currently set title. If {@link #titleRes} is set,
* this resource is loaded from <var>res</var> and returned. Otherwise
* {@link #title} is returned.
*/
public CharSequence getTitle(Resources res) {
if (titleRes != 0) {
return res.getText(titleRes);
}
return title;
}
/**
* Return the currently set summary. If {@link #summaryRes} is set,
* this resource is loaded from <var>res</var> and returned. Otherwise
* {@link #summary} is returned.
*/
public CharSequence getSummary(Resources res) {
if (summaryRes != 0) {
return res.getText(summaryRes);
}
return summary;
}
/**
* Return the currently set bread crumb title. If {@link #breadCrumbTitleRes} is set,
* this resource is loaded from <var>res</var> and returned. Otherwise
* {@link #breadCrumbTitle} is returned.
*/
public CharSequence getBreadCrumbTitle(Resources res) {
if (breadCrumbTitleRes != 0) {
return res.getText(breadCrumbTitleRes);
}
return breadCrumbTitle;
}
/**
* Return the currently set bread crumb short title. If
* {@link #breadCrumbShortTitleRes} is set,
* this resource is loaded from <var>res</var> and returned. Otherwise
* {@link #breadCrumbShortTitle} is returned.
*/
public CharSequence getBreadCrumbShortTitle(Resources res) {
if (breadCrumbShortTitleRes != 0) {
return res.getText(breadCrumbShortTitleRes);
}
return breadCrumbShortTitle;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeInt(titleRes);
TextUtils.writeToParcel(title, dest, flags);
dest.writeInt(summaryRes);
TextUtils.writeToParcel(summary, dest, flags);
dest.writeInt(breadCrumbTitleRes);
TextUtils.writeToParcel(breadCrumbTitle, dest, flags);
dest.writeInt(breadCrumbShortTitleRes);
TextUtils.writeToParcel(breadCrumbShortTitle, dest, flags);
dest.writeInt(iconRes);
dest.writeString(fragment);
dest.writeBundle(fragmentArguments);
if (intent != null) {
dest.writeInt(1);
intent.writeToParcel(dest, flags);
} else {
dest.writeInt(0);
}
dest.writeBundle(extras);
}
public void readFromParcel(Parcel in) {
id = in.readLong();
titleRes = in.readInt();
title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
summaryRes = in.readInt();
summary = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
breadCrumbTitleRes = in.readInt();
breadCrumbTitle = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
breadCrumbShortTitleRes = in.readInt();
breadCrumbShortTitle = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
iconRes = in.readInt();
fragment = in.readString();
fragmentArguments = in.readBundle();
if (in.readInt() != 0) {
intent = Intent.CREATOR.createFromParcel(in);
}
extras = in.readBundle();
}
Header(Parcel in) {
readFromParcel(in);
}
public static final @android.annotation.NonNull Creator<Header> CREATOR = new Creator<Header>() {
public Header createFromParcel(Parcel source) {
return new Header(source);
}
public Header[] newArray(int size) {
return new Header[size];
}
};
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
// Override home navigation button to call onBackPressed (b/35152749).
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Theming for the PreferenceActivity layout and for the Preference Header(s) layout
TypedArray sa = obtainStyledAttributes(null,
com.android.internal.R.styleable.PreferenceActivity,
com.android.internal.R.attr.preferenceActivityStyle,
0);
final int layoutResId = sa.getResourceId(
com.android.internal.R.styleable.PreferenceActivity_layout,
com.android.internal.R.layout.preference_list_content);
mPreferenceHeaderItemResId = sa.getResourceId(
com.android.internal.R.styleable.PreferenceActivity_headerLayout,
com.android.internal.R.layout.preference_header_item);
mPreferenceHeaderRemoveEmptyIcon = sa.getBoolean(
com.android.internal.R.styleable.PreferenceActivity_headerRemoveIconIfEmpty,
false);
sa.recycle();
setContentView(layoutResId);
mListFooter = (FrameLayout)findViewById(com.android.internal.R.id.list_footer);
mPrefsContainer = (ViewGroup) findViewById(com.android.internal.R.id.prefs_frame);
mHeadersContainer = (ViewGroup) findViewById(com.android.internal.R.id.headers);
boolean hidingHeaders = onIsHidingHeaders();
mSinglePane = hidingHeaders || !onIsMultiPane();
String initialFragment = getIntent().getStringExtra(EXTRA_SHOW_FRAGMENT);
Bundle initialArguments = getIntent().getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS);
int initialTitle = getIntent().getIntExtra(EXTRA_SHOW_FRAGMENT_TITLE, 0);
int initialShortTitle = getIntent().getIntExtra(EXTRA_SHOW_FRAGMENT_SHORT_TITLE, 0);
mActivityTitle = getTitle();
if (savedInstanceState != null) {
// We are restarting from a previous saved state; used that to
// initialize, instead of starting fresh.
ArrayList<Header> headers = savedInstanceState.getParcelableArrayList(HEADERS_TAG);
if (headers != null) {
mHeaders.addAll(headers);
int curHeader = savedInstanceState.getInt(CUR_HEADER_TAG,
(int) HEADER_ID_UNDEFINED);
if (curHeader >= 0 && curHeader < mHeaders.size()) {
setSelectedHeader(mHeaders.get(curHeader));
} else if (!mSinglePane && initialFragment == null) {
switchToHeader(onGetInitialHeader());
}
} else {
// This will for instance hide breadcrumbs for single pane.
showBreadCrumbs(getTitle(), null);
}
} else {
if (!onIsHidingHeaders()) {
onBuildHeaders(mHeaders);
}
if (initialFragment != null) {
switchToHeader(initialFragment, initialArguments);
} else if (!mSinglePane && mHeaders.size() > 0) {
switchToHeader(onGetInitialHeader());
}
}
if (mHeaders.size() > 0) {
setListAdapter(new HeaderAdapter(this, mHeaders, mPreferenceHeaderItemResId,
mPreferenceHeaderRemoveEmptyIcon));
if (!mSinglePane) {
getListView().setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
}
}
if (mSinglePane && initialFragment != null && initialTitle != 0) {
CharSequence initialTitleStr = getText(initialTitle);
CharSequence initialShortTitleStr = initialShortTitle != 0
? getText(initialShortTitle) : null;
showBreadCrumbs(initialTitleStr, initialShortTitleStr);
}
if (mHeaders.size() == 0 && initialFragment == null) {
// If there are no headers, we are in the old "just show a screen
// of preferences" mode.
setContentView(com.android.internal.R.layout.preference_list_content_single);
mListFooter = (FrameLayout) findViewById(com.android.internal.R.id.list_footer);
mPrefsContainer = (ViewGroup) findViewById(com.android.internal.R.id.prefs);
mPreferenceManager = new PreferenceManager(this, FIRST_REQUEST_CODE);
mPreferenceManager.setOnPreferenceTreeClickListener(this);
mHeadersContainer = null;
} else if (mSinglePane) {
// Single-pane so one of the header or prefs containers must be hidden.
if (initialFragment != null || mCurHeader != null) {
mHeadersContainer.setVisibility(View.GONE);
} else {
mPrefsContainer.setVisibility(View.GONE);
}
// This animates our manual transitions between headers and prefs panel in single-pane.
// It also comes last so we don't animate any initial layout changes done above.
ViewGroup container = (ViewGroup) findViewById(
com.android.internal.R.id.prefs_container);
container.setLayoutTransition(new LayoutTransition());
} else {
// Multi-pane
if (mHeaders.size() > 0 && mCurHeader != null) {
setSelectedHeader(mCurHeader);
}
}
// see if we should show Back/Next buttons
Intent intent = getIntent();
if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_BUTTON_BAR, false)) {
findViewById(com.android.internal.R.id.button_bar).setVisibility(View.VISIBLE);
Button backButton = (Button)findViewById(com.android.internal.R.id.back_button);
backButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setResult(RESULT_CANCELED);
finish();
}
});
Button skipButton = (Button)findViewById(com.android.internal.R.id.skip_button);
skipButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
mNextButton = (Button)findViewById(com.android.internal.R.id.next_button);
mNextButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
// set our various button parameters
if (intent.hasExtra(EXTRA_PREFS_SET_NEXT_TEXT)) {
String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_NEXT_TEXT);
if (TextUtils.isEmpty(buttonText)) {
mNextButton.setVisibility(View.GONE);
}
else {
mNextButton.setText(buttonText);
}
}
if (intent.hasExtra(EXTRA_PREFS_SET_BACK_TEXT)) {
String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_BACK_TEXT);
if (TextUtils.isEmpty(buttonText)) {
backButton.setVisibility(View.GONE);
}
else {
backButton.setText(buttonText);
}
}
if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_SKIP, false)) {
skipButton.setVisibility(View.VISIBLE);
}
}
}
@Override
public void onBackPressed() {
if (mCurHeader != null && mSinglePane && getFragmentManager().getBackStackEntryCount() == 0
&& getIntent().getStringExtra(EXTRA_SHOW_FRAGMENT) == null) {
mCurHeader = null;
mPrefsContainer.setVisibility(View.GONE);
mHeadersContainer.setVisibility(View.VISIBLE);
if (mActivityTitle != null) {
showBreadCrumbs(mActivityTitle, null);
}
getListView().clearChoices();
} else {
super.onBackPressed();
}
}
/**
* Returns true if this activity is currently showing the header list.
*/
public boolean hasHeaders() {
return mHeadersContainer != null && mHeadersContainer.getVisibility() == View.VISIBLE;
}
/**
* Returns the Header list
* @hide
*/
@UnsupportedAppUsage
public List<Header> getHeaders() {
return mHeaders;
}
/**
* Returns true if this activity is showing multiple panes -- the headers
* and a preference fragment.
*/
public boolean isMultiPane() {
return !mSinglePane;
}
/**
* Called to determine if the activity should run in multi-pane mode.
* The default implementation returns true if the screen is large
* enough.
*/
public boolean onIsMultiPane() {
boolean preferMultiPane = getResources().getBoolean(
com.android.internal.R.bool.preferences_prefer_dual_pane);
return preferMultiPane;
}
/**
* Called to determine whether the header list should be hidden.
* The default implementation returns the
* value given in {@link #EXTRA_NO_HEADERS} or false if it is not supplied.
* This is set to false, for example, when the activity is being re-launched
* to show a particular preference activity.
*/
public boolean onIsHidingHeaders() {
return getIntent().getBooleanExtra(EXTRA_NO_HEADERS, false);
}
/**
* Called to determine the initial header to be shown. The default
* implementation simply returns the fragment of the first header. Note
* that the returned Header object does not actually need to exist in
* your header list -- whatever its fragment is will simply be used to
* show for the initial UI.
*/
public Header onGetInitialHeader() {
for (int i=0; i<mHeaders.size(); i++) {
Header h = mHeaders.get(i);
if (h.fragment != null) {
return h;
}
}
throw new IllegalStateException("Must have at least one header with a fragment");
}
/**
* Called after the header list has been updated ({@link #onBuildHeaders}
* has been called and returned due to {@link #invalidateHeaders()}) to
* specify the header that should now be selected. The default implementation
* returns null to keep whatever header is currently selected.
*/
public Header onGetNewHeader() {
return null;
}
/**
* Called when the activity needs its list of headers build. By
* implementing this and adding at least one item to the list, you
* will cause the activity to run in its modern fragment mode. Note
* that this function may not always be called; for example, if the
* activity has been asked to display a particular fragment without
* the header list, there is no need to build the headers.
*
* <p>Typical implementations will use {@link #loadHeadersFromResource}
* to fill in the list from a resource.
*
* @param target The list in which to place the headers.
*/
public void onBuildHeaders(List<Header> target) {
// Should be overloaded by subclasses
}
/**
* Call when you need to change the headers being displayed. Will result
* in onBuildHeaders() later being called to retrieve the new list.
*/
public void invalidateHeaders() {
if (!mHandler.hasMessages(MSG_BUILD_HEADERS)) {
mHandler.sendEmptyMessage(MSG_BUILD_HEADERS);
}
}
/**
* Parse the given XML file as a header description, adding each
* parsed Header into the target list.
*
* @param resid The XML resource to load and parse.
* @param target The list in which the parsed headers should be placed.
*/
public void loadHeadersFromResource(@XmlRes int resid, List<Header> target) {
XmlResourceParser parser = null;
try {
parser = getResources().getXml(resid);
AttributeSet attrs = Xml.asAttributeSet(parser);
int type;
while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
&& type != XmlPullParser.START_TAG) {
// Parse next until start tag is found
}
String nodeName = parser.getName();
if (!"preference-headers".equals(nodeName)) {
throw new RuntimeException(
"XML document must start with <preference-headers> tag; found"
+ nodeName + " at " + parser.getPositionDescription());
}
Bundle curBundle = null;
final int outerDepth = parser.getDepth();
while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
&& (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
continue;
}
nodeName = parser.getName();
if ("header".equals(nodeName)) {
Header header = new Header();
TypedArray sa = obtainStyledAttributes(
attrs, com.android.internal.R.styleable.PreferenceHeader);
header.id = sa.getResourceId(
com.android.internal.R.styleable.PreferenceHeader_id,
(int)HEADER_ID_UNDEFINED);
TypedValue tv = sa.peekValue(
com.android.internal.R.styleable.PreferenceHeader_title);
if (tv != null && tv.type == TypedValue.TYPE_STRING) {
if (tv.resourceId != 0) {
header.titleRes = tv.resourceId;
} else {
header.title = tv.string;
}
}
tv = sa.peekValue(
com.android.internal.R.styleable.PreferenceHeader_summary);
if (tv != null && tv.type == TypedValue.TYPE_STRING) {
if (tv.resourceId != 0) {
header.summaryRes = tv.resourceId;
} else {
header.summary = tv.string;
}
}
tv = sa.peekValue(
com.android.internal.R.styleable.PreferenceHeader_breadCrumbTitle);
if (tv != null && tv.type == TypedValue.TYPE_STRING) {
if (tv.resourceId != 0) {
header.breadCrumbTitleRes = tv.resourceId;
} else {
header.breadCrumbTitle = tv.string;
}
}
tv = sa.peekValue(
com.android.internal.R.styleable.PreferenceHeader_breadCrumbShortTitle);
if (tv != null && tv.type == TypedValue.TYPE_STRING) {
if (tv.resourceId != 0) {
header.breadCrumbShortTitleRes = tv.resourceId;
} else {
header.breadCrumbShortTitle = tv.string;
}
}
header.iconRes = sa.getResourceId(
com.android.internal.R.styleable.PreferenceHeader_icon, 0);
header.fragment = sa.getString(
com.android.internal.R.styleable.PreferenceHeader_fragment);
sa.recycle();
if (curBundle == null) {
curBundle = new Bundle();
}
final int innerDepth = parser.getDepth();
while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
&& (type != XmlPullParser.END_TAG || parser.getDepth() > innerDepth)) {
if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
continue;
}
String innerNodeName = parser.getName();
if (innerNodeName.equals("extra")) {
getResources().parseBundleExtra("extra", attrs, curBundle);
XmlUtils.skipCurrentTag(parser);
} else if (innerNodeName.equals("intent")) {
header.intent = Intent.parseIntent(getResources(), parser, attrs);
} else {
XmlUtils.skipCurrentTag(parser);
}
}
if (curBundle.size() > 0) {
header.fragmentArguments = curBundle;
curBundle = null;
}
target.add(header);
} else {
XmlUtils.skipCurrentTag(parser);
}
}
} catch (XmlPullParserException e) {
throw new RuntimeException("Error parsing headers", e);
} catch (IOException e) {
throw new RuntimeException("Error parsing headers", e);
} finally {
if (parser != null) parser.close();
}
}
/**
* Subclasses should override this method and verify that the given fragment is a valid type
* to be attached to this activity. The default implementation returns <code>true</code> for
* apps built for <code>android:targetSdkVersion</code> older than
* {@link android.os.Build.VERSION_CODES#KITKAT}. For later versions, it will throw an exception.
* @param fragmentName the class name of the Fragment about to be attached to this activity.
* @return true if the fragment class name is valid for this Activity and false otherwise.
*/
protected boolean isValidFragment(String fragmentName) {
if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.KITKAT) {
throw new RuntimeException(
"Subclasses of PreferenceActivity must override isValidFragment(String)"
+ " to verify that the Fragment class is valid! "
+ this.getClass().getName()
+ " has not checked if fragment " + fragmentName + " is valid.");
} else {
return true;
}
}
/**
* Set a footer that should be shown at the bottom of the header list.
*/
public void setListFooter(View view) {
mListFooter.removeAllViews();
mListFooter.addView(view, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT));
}
@Override
protected void onStop() {
super.onStop();
if (mPreferenceManager != null) {
mPreferenceManager.dispatchActivityStop();
}
}
@Override
protected void onDestroy() {
mHandler.removeMessages(MSG_BIND_PREFERENCES);
mHandler.removeMessages(MSG_BUILD_HEADERS);
super.onDestroy();
if (mPreferenceManager != null) {
mPreferenceManager.dispatchActivityDestroy();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mHeaders.size() > 0) {
outState.putParcelableArrayList(HEADERS_TAG, mHeaders);
if (mCurHeader != null) {
int index = mHeaders.indexOf(mCurHeader);
if (index >= 0) {
outState.putInt(CUR_HEADER_TAG, index);
}
}
}
if (mPreferenceManager != null) {
final PreferenceScreen preferenceScreen = getPreferenceScreen();
if (preferenceScreen != null) {
Bundle container = new Bundle();
preferenceScreen.saveHierarchyState(container);
outState.putBundle(PREFERENCES_TAG, container);
}
}
}
@Override
protected void onRestoreInstanceState(Bundle state) {
if (mPreferenceManager != null) {
Bundle container = state.getBundle(PREFERENCES_TAG);
if (container != null) {
final PreferenceScreen preferenceScreen = getPreferenceScreen();
if (preferenceScreen != null) {
preferenceScreen.restoreHierarchyState(container);
mSavedInstanceState = state;
return;
}
}
}
// Only call this if we didn't save the instance state for later.
// If we did save it, it will be restored when we bind the adapter.
super.onRestoreInstanceState(state);
if (!mSinglePane) {
// Multi-pane.
if (mCurHeader != null) {
setSelectedHeader(mCurHeader);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (mPreferenceManager != null) {
mPreferenceManager.dispatchActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onContentChanged() {
super.onContentChanged();
if (mPreferenceManager != null) {
postBindPreferences();
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
if (!isResumed()) {
return;
}
super.onListItemClick(l, v, position, id);
if (mAdapter != null) {
Object item = mAdapter.getItem(position);
if (item instanceof Header) onHeaderClick((Header) item, position);
}
}
/**
* Called when the user selects an item in the header list. The default
* implementation will call either
* {@link #startWithFragment(String, Bundle, Fragment, int, int, int)}
* or {@link #switchToHeader(Header)} as appropriate.
*
* @param header The header that was selected.
* @param position The header's position in the list.
*/
public void onHeaderClick(Header header, int position) {
if (header.fragment != null) {
switchToHeader(header);
} else if (header.intent != null) {
startActivity(header.intent);
}
}
/**
* Called by {@link #startWithFragment(String, Bundle, Fragment, int, int, int)} when
* in single-pane mode, to build an Intent to launch a new activity showing
* the selected fragment. The default implementation constructs an Intent
* that re-launches the current activity with the appropriate arguments to
* display the fragment.
*
* @param fragmentName The name of the fragment to display.
* @param args Optional arguments to supply to the fragment.
* @param titleRes Optional resource ID of title to show for this item.
* @param shortTitleRes Optional resource ID of short title to show for this item.
* @return Returns an Intent that can be launched to display the given
* fragment.
*/
public Intent onBuildStartFragmentIntent(String fragmentName, Bundle args,
@StringRes int titleRes, int shortTitleRes) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(this, getClass());
intent.putExtra(EXTRA_SHOW_FRAGMENT, fragmentName);
intent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
intent.putExtra(EXTRA_SHOW_FRAGMENT_TITLE, titleRes);
intent.putExtra(EXTRA_SHOW_FRAGMENT_SHORT_TITLE, shortTitleRes);
intent.putExtra(EXTRA_NO_HEADERS, true);
return intent;
}
/**
* Like {@link #startWithFragment(String, Bundle, Fragment, int, int, int)}
* but uses a 0 titleRes.
*/
public void startWithFragment(String fragmentName, Bundle args,
Fragment resultTo, int resultRequestCode) {
startWithFragment(fragmentName, args, resultTo, resultRequestCode, 0, 0);
}
/**
* Start a new instance of this activity, showing only the given
* preference fragment. When launched in this mode, the header list
* will be hidden and the given preference fragment will be instantiated
* and fill the entire activity.
*
* @param fragmentName The name of the fragment to display.
* @param args Optional arguments to supply to the fragment.
* @param resultTo Option fragment that should receive the result of
* the activity launch.
* @param resultRequestCode If resultTo is non-null, this is the request
* code in which to report the result.
* @param titleRes Resource ID of string to display for the title of
* this set of preferences.
* @param shortTitleRes Resource ID of string to display for the short title of
* this set of preferences.
*/
public void startWithFragment(String fragmentName, Bundle args,
Fragment resultTo, int resultRequestCode, @StringRes int titleRes,
@StringRes int shortTitleRes) {
Intent intent = onBuildStartFragmentIntent(fragmentName, args, titleRes, shortTitleRes);
if (resultTo == null) {
startActivity(intent);
} else {
resultTo.startActivityForResult(intent, resultRequestCode);
}
}
/**
* Change the base title of the bread crumbs for the current preferences.
* This will normally be called for you. See
* {@link android.app.FragmentBreadCrumbs} for more information.
*/
public void showBreadCrumbs(CharSequence title, CharSequence shortTitle) {
if (mFragmentBreadCrumbs == null) {
View crumbs = findViewById(android.R.id.title);
// For screens with a different kind of title, don't create breadcrumbs.
try {
mFragmentBreadCrumbs = (FragmentBreadCrumbs)crumbs;
} catch (ClassCastException e) {
setTitle(title);
return;
}
if (mFragmentBreadCrumbs == null) {
if (title != null) {
setTitle(title);
}
return;
}
if (mSinglePane) {
mFragmentBreadCrumbs.setVisibility(View.GONE);
// Hide the breadcrumb section completely for single-pane
View bcSection = findViewById(com.android.internal.R.id.breadcrumb_section);
if (bcSection != null) bcSection.setVisibility(View.GONE);
setTitle(title);
}
mFragmentBreadCrumbs.setMaxVisible(2);
mFragmentBreadCrumbs.setActivity(this);
}
if (mFragmentBreadCrumbs.getVisibility() != View.VISIBLE) {
setTitle(title);
} else {
mFragmentBreadCrumbs.setTitle(title, shortTitle);
mFragmentBreadCrumbs.setParentTitle(null, null, null);
}
}
/**
* Should be called after onCreate to ensure that the breadcrumbs, if any, were created.
* This prepends a title to the fragment breadcrumbs and attaches a listener to any clicks
* on the parent entry.
* @param title the title for the breadcrumb
* @param shortTitle the short title for the breadcrumb
*/
public void setParentTitle(CharSequence title, CharSequence shortTitle,
OnClickListener listener) {
if (mFragmentBreadCrumbs != null) {
mFragmentBreadCrumbs.setParentTitle(title, shortTitle, listener);
}
}
void setSelectedHeader(Header header) {
mCurHeader = header;
int index = mHeaders.indexOf(header);
if (index >= 0) {
getListView().setItemChecked(index, true);
} else {
getListView().clearChoices();
}
showBreadCrumbs(header);
}
void showBreadCrumbs(Header header) {
if (header != null) {
CharSequence title = header.getBreadCrumbTitle(getResources());
if (title == null) title = header.getTitle(getResources());
if (title == null) title = getTitle();
showBreadCrumbs(title, header.getBreadCrumbShortTitle(getResources()));
} else {
showBreadCrumbs(getTitle(), null);
}
}
private void switchToHeaderInner(String fragmentName, Bundle args) {
getFragmentManager().popBackStack(BACK_STACK_PREFS,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
if (!isValidFragment(fragmentName)) {
throw new IllegalArgumentException("Invalid fragment for this activity: "
+ fragmentName);
}
Fragment f = Fragment.instantiate(this, fragmentName, args);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setTransition(mSinglePane
? FragmentTransaction.TRANSIT_NONE
: FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.replace(com.android.internal.R.id.prefs, f);
transaction.commitAllowingStateLoss();
if (mSinglePane && mPrefsContainer.getVisibility() == View.GONE) {
// We are transitioning from headers to preferences panel in single-pane so we need
// to hide headers and show the prefs container.
mPrefsContainer.setVisibility(View.VISIBLE);
mHeadersContainer.setVisibility(View.GONE);
}
}
/**
* When in two-pane mode, switch the fragment pane to show the given
* preference fragment.
*
* @param fragmentName The name of the fragment to display.
* @param args Optional arguments to supply to the fragment.
*/
public void switchToHeader(String fragmentName, Bundle args) {
Header selectedHeader = null;
for (int i = 0; i < mHeaders.size(); i++) {
if (fragmentName.equals(mHeaders.get(i).fragment)) {
selectedHeader = mHeaders.get(i);
break;
}
}
setSelectedHeader(selectedHeader);
switchToHeaderInner(fragmentName, args);
}
/**
* When in two-pane mode, switch to the fragment pane to show the given
* preference fragment.
*
* @param header The new header to display.
*/
public void switchToHeader(Header header) {
if (mCurHeader == header) {
// This is the header we are currently displaying. Just make sure
// to pop the stack up to its root state.
getFragmentManager().popBackStack(BACK_STACK_PREFS,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
if (header.fragment == null) {
throw new IllegalStateException("can't switch to header that has no fragment");
}
switchToHeaderInner(header.fragment, header.fragmentArguments);
setSelectedHeader(header);
}
}
Header findBestMatchingHeader(Header cur, ArrayList<Header> from) {
ArrayList<Header> matches = new ArrayList<Header>();
for (int j=0; j<from.size(); j++) {
Header oh = from.get(j);
if (cur == oh || (cur.id != HEADER_ID_UNDEFINED && cur.id == oh.id)) {
// Must be this one.
matches.clear();
matches.add(oh);
break;
}
if (cur.fragment != null) {
if (cur.fragment.equals(oh.fragment)) {
matches.add(oh);
}
} else if (cur.intent != null) {
if (cur.intent.equals(oh.intent)) {
matches.add(oh);
}
} else if (cur.title != null) {
if (cur.title.equals(oh.title)) {
matches.add(oh);
}
}
}
final int NM = matches.size();
if (NM == 1) {
return matches.get(0);
} else if (NM > 1) {
for (int j=0; j<NM; j++) {
Header oh = matches.get(j);
if (cur.fragmentArguments != null &&
cur.fragmentArguments.equals(oh.fragmentArguments)) {
return oh;
}
if (cur.extras != null && cur.extras.equals(oh.extras)) {
return oh;
}
if (cur.title != null && cur.title.equals(oh.title)) {
return oh;
}
}
}
return null;
}
/**
* Start a new fragment.
*
* @param fragment The fragment to start
* @param push If true, the current fragment will be pushed onto the back stack. If false,
* the current fragment will be replaced.
*/
public void startPreferenceFragment(Fragment fragment, boolean push) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(com.android.internal.R.id.prefs, fragment);
if (push) {
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(BACK_STACK_PREFS);
} else {
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
}
transaction.commitAllowingStateLoss();
}
/**
* Start a new fragment containing a preference panel. If the preferences
* are being displayed in multi-pane mode, the given fragment class will
* be instantiated and placed in the appropriate pane. If running in
* single-pane mode, a new activity will be launched in which to show the
* fragment.
*
* @param fragmentClass Full name of the class implementing the fragment.
* @param args Any desired arguments to supply to the fragment.
* @param titleRes Optional resource identifier of the title of this
* fragment.
* @param titleText Optional text of the title of this fragment.
* @param resultTo Optional fragment that result data should be sent to.
* If non-null, resultTo.onActivityResult() will be called when this
* preference panel is done. The launched panel must use
* {@link #finishPreferencePanel(Fragment, int, Intent)} when done.
* @param resultRequestCode If resultTo is non-null, this is the caller's
* request code to be received with the result.
*/
public void startPreferencePanel(String fragmentClass, Bundle args, @StringRes int titleRes,
CharSequence titleText, Fragment resultTo, int resultRequestCode) {
Fragment f = Fragment.instantiate(this, fragmentClass, args);
if (resultTo != null) {
f.setTargetFragment(resultTo, resultRequestCode);
}
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(com.android.internal.R.id.prefs, f);
if (titleRes != 0) {
transaction.setBreadCrumbTitle(titleRes);
} else if (titleText != null) {
transaction.setBreadCrumbTitle(titleText);
}
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(BACK_STACK_PREFS);
transaction.commitAllowingStateLoss();
}
/**
* Called by a preference panel fragment to finish itself.
*
* @param caller The fragment that is asking to be finished.
* @param resultCode Optional result code to send back to the original
* launching fragment.
* @param resultData Optional result data to send back to the original
* launching fragment.
*/
public void finishPreferencePanel(Fragment caller, int resultCode, Intent resultData) {
// TODO: be smarter about popping the stack.
onBackPressed();
if (caller != null) {
if (caller.getTargetFragment() != null) {
caller.getTargetFragment().onActivityResult(caller.getTargetRequestCode(),
resultCode, resultData);
}
}
}
@Override
public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) {
startPreferencePanel(pref.getFragment(), pref.getExtras(), pref.getTitleRes(),
pref.getTitle(), null, 0);
return true;
}
/**
* Posts a message to bind the preferences to the list view.
* <p>
* Binding late is preferred as any custom preference types created in
* {@link #onCreate(Bundle)} are able to have their views recycled.
*/
@UnsupportedAppUsage
private void postBindPreferences() {
if (mHandler.hasMessages(MSG_BIND_PREFERENCES)) return;
mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget();
}
private void bindPreferences() {
final PreferenceScreen preferenceScreen = getPreferenceScreen();
if (preferenceScreen != null) {
preferenceScreen.bind(getListView());
if (mSavedInstanceState != null) {
super.onRestoreInstanceState(mSavedInstanceState);
mSavedInstanceState = null;
}
}
}
/**
* Returns the {@link PreferenceManager} used by this activity.
* @return The {@link PreferenceManager}.
*
* @deprecated This function is not relevant for a modern fragment-based
* PreferenceActivity.
*/
@Deprecated
public PreferenceManager getPreferenceManager() {
return mPreferenceManager;
}
@UnsupportedAppUsage
private void requirePreferenceManager() {
if (mPreferenceManager == null) {
if (mAdapter == null) {
throw new RuntimeException("This should be called after super.onCreate.");
}
throw new RuntimeException(
"Modern two-pane PreferenceActivity requires use of a PreferenceFragment");
}
}
/**
* Sets the root of the preference hierarchy that this activity is showing.
*
* @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.
*
* @deprecated This function is not relevant for a modern fragment-based
* PreferenceActivity.
*/
@Deprecated
public void setPreferenceScreen(PreferenceScreen preferenceScreen) {
requirePreferenceManager();
if (mPreferenceManager.setPreferences(preferenceScreen) && preferenceScreen != null) {
postBindPreferences();
CharSequence title = getPreferenceScreen().getTitle();
// Set the title of the activity
if (title != null) {
setTitle(title);
}
}
}
/**
* Gets the root of the preference hierarchy that this activity is showing.
*
* @return The {@link PreferenceScreen} that is the root of the preference
* hierarchy.
*
* @deprecated This function is not relevant for a modern fragment-based
* PreferenceActivity.
*/
@Deprecated
public PreferenceScreen getPreferenceScreen() {
if (mPreferenceManager != null) {
return mPreferenceManager.getPreferenceScreen();
}
return null;
}
/**
* Adds preferences from activities that match the given {@link Intent}.
*
* @param intent The {@link Intent} to query activities.
*
* @deprecated This function is not relevant for a modern fragment-based
* PreferenceActivity.
*/
@Deprecated
public void addPreferencesFromIntent(Intent intent) {
requirePreferenceManager();
setPreferenceScreen(mPreferenceManager.inflateFromIntent(intent, getPreferenceScreen()));
}
/**
* Inflates the given XML resource and adds the preference hierarchy to the current
* preference hierarchy.
*
* @param preferencesResId The XML resource ID to inflate.
*
* @deprecated This function is not relevant for a modern fragment-based
* PreferenceActivity.
*/
@Deprecated
public void addPreferencesFromResource(int preferencesResId) {
requirePreferenceManager();
setPreferenceScreen(mPreferenceManager.inflateFromResource(this, preferencesResId,
getPreferenceScreen()));
}
/**
* {@inheritDoc}
*
* @deprecated This function is not relevant for a modern fragment-based
* PreferenceActivity.
*/
@Deprecated
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
return false;
}
/**
* Finds a {@link Preference} based on its key.
*
* @param key The key of the preference to retrieve.
* @return The {@link Preference} with the key, or null.
* @see PreferenceGroup#findPreference(CharSequence)
*
* @deprecated This function is not relevant for a modern fragment-based
* PreferenceActivity.
*/
@Deprecated
public Preference findPreference(CharSequence key) {
if (mPreferenceManager == null) {
return null;
}
return mPreferenceManager.findPreference(key);
}
@Override
protected void onNewIntent(Intent intent) {
if (mPreferenceManager != null) {
mPreferenceManager.dispatchNewIntent(intent);
}
}
// give subclasses access to the Next button
/** @hide */
protected boolean hasNextButton() {
return mNextButton != null;
}
/** @hide */
protected Button getNextButton() {
return mNextButton;
}
}
|