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 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123
|
/*
* 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.annotation.CallSuper;
import android.annotation.DrawableRes;
import android.annotation.LayoutRes;
import android.annotation.Nullable;
import android.annotation.StringRes;
import android.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.AbsSavedState;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.internal.util.CharSequences;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Represents the basic Preference UI building
* block displayed by a {@link PreferenceActivity} in the form of a
* {@link ListView}. This class provides the {@link View} to be displayed in
* the activity and associates with a {@link SharedPreferences} to
* store/retrieve the preference data.
* <p>
* When specifying a preference hierarchy in XML, each element can point to a
* subclass of {@link Preference}, similar to the view hierarchy and layouts.
* <p>
* This class contains a {@code key} that will be used as the key into the
* {@link SharedPreferences}. It is up to the subclass to decide how to store
* the value.
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For information about building a settings UI with Preferences,
* read the <a href="{@docRoot}guide/topics/ui/settings.html">Settings</a>
* guide.</p>
* </div>
*
* @attr ref android.R.styleable#Preference_icon
* @attr ref android.R.styleable#Preference_key
* @attr ref android.R.styleable#Preference_title
* @attr ref android.R.styleable#Preference_summary
* @attr ref android.R.styleable#Preference_order
* @attr ref android.R.styleable#Preference_fragment
* @attr ref android.R.styleable#Preference_layout
* @attr ref android.R.styleable#Preference_widgetLayout
* @attr ref android.R.styleable#Preference_enabled
* @attr ref android.R.styleable#Preference_selectable
* @attr ref android.R.styleable#Preference_dependency
* @attr ref android.R.styleable#Preference_persistent
* @attr ref android.R.styleable#Preference_defaultValue
* @attr ref android.R.styleable#Preference_shouldDisableView
* @attr ref android.R.styleable#Preference_recycleEnabled
* @attr ref android.R.styleable#Preference_singleLineTitle
* @attr ref android.R.styleable#Preference_iconSpaceReserved
*
* @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 class Preference implements Comparable<Preference> {
/**
* Specify for {@link #setOrder(int)} if a specific order is not required.
*/
public static final int DEFAULT_ORDER = Integer.MAX_VALUE;
private Context mContext;
@Nullable
private PreferenceManager mPreferenceManager;
/**
* The data store that should be used by this Preference to store / retrieve data. If null then
* {@link PreferenceManager#getPreferenceDataStore()} needs to be checked. If that one is null
* too it means that we are using {@link android.content.SharedPreferences} to store the data.
*/
@Nullable
private PreferenceDataStore mPreferenceDataStore;
/**
* Set when added to hierarchy since we need a unique ID within that
* hierarchy.
*/
private long mId;
private OnPreferenceChangeListener mOnChangeListener;
private OnPreferenceClickListener mOnClickListener;
private int mOrder = DEFAULT_ORDER;
private CharSequence mTitle;
private int mTitleRes;
@UnsupportedAppUsage
private CharSequence mSummary;
/**
* mIconResId is overridden by mIcon, if mIcon is specified.
*/
private int mIconResId;
private Drawable mIcon;
private String mKey;
private Intent mIntent;
private String mFragment;
private Bundle mExtras;
private boolean mEnabled = true;
private boolean mSelectable = true;
private boolean mRequiresKey;
private boolean mPersistent = true;
private String mDependencyKey;
private Object mDefaultValue;
private boolean mDependencyMet = true;
private boolean mParentDependencyMet = true;
private boolean mRecycleEnabled = true;
private boolean mHasSingleLineTitleAttr;
private boolean mSingleLineTitle = true;
private boolean mIconSpaceReserved;
/**
* @see #setShouldDisableView(boolean)
*/
private boolean mShouldDisableView = true;
@UnsupportedAppUsage
private int mLayoutResId = com.android.internal.R.layout.preference;
@UnsupportedAppUsage
private int mWidgetLayoutResId;
private OnPreferenceChangeInternalListener mListener;
private List<Preference> mDependents;
private PreferenceGroup mParentGroup;
private boolean mBaseMethodCalled;
/**
* Interface definition for a callback to be invoked when the value of this
* {@link Preference} has been changed by the user and is
* about to be set and/or persisted. This gives the client a chance
* to prevent setting and/or persisting the value.
*
* @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 interface OnPreferenceChangeListener {
/**
* Called when a Preference has been changed by the user. This is
* called before the state of the Preference is about to be updated and
* before the state is persisted.
*
* @param preference The changed Preference.
* @param newValue The new value of the Preference.
* @return True to update the state of the Preference with the new value.
*/
boolean onPreferenceChange(Preference preference, Object newValue);
}
/**
* Interface definition for a callback to be invoked when a {@link Preference} is
* clicked.
*
* @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 interface OnPreferenceClickListener {
/**
* Called when a Preference has been clicked.
*
* @param preference The Preference that was clicked.
* @return True if the click was handled.
*/
boolean onPreferenceClick(Preference preference);
}
/**
* Interface definition for a callback to be invoked when this
* {@link Preference} is changed or, if this is a group, there is an
* addition/removal of {@link Preference}(s). This is used internally.
*/
interface OnPreferenceChangeInternalListener {
/**
* Called when this Preference has changed.
*
* @param preference This preference.
*/
void onPreferenceChange(Preference preference);
/**
* Called when this group has added/removed {@link Preference}(s).
*
* @param preference This Preference.
*/
void onPreferenceHierarchyChange(Preference preference);
}
/**
* Perform inflation from XML and apply a class-specific base style. This
* constructor of Preference allows subclasses to use their own base style
* when they are inflating. For example, a {@link CheckBoxPreference}
* constructor calls this version of the super class constructor and
* supplies {@code android.R.attr.checkBoxPreferenceStyle} for
* <var>defStyleAttr</var>. This allows the theme's checkbox preference
* style to modify all of the base preference attributes as well as the
* {@link CheckBoxPreference} class's attributes.
*
* @param context The Context this is associated with, through which it can
* access the current theme, resources,
* {@link SharedPreferences}, etc.
* @param attrs The attributes of the XML tag that is inflating the
* preference.
* @param defStyleAttr An attribute in the current theme that contains a
* reference to a style resource that supplies default values for
* the view. Can be 0 to not look for defaults.
* @param defStyleRes A resource identifier of a style resource that
* supplies default values for the view, used only if
* defStyleAttr is 0 or can not be found in the theme. Can be 0
* to not look for defaults.
* @see #Preference(Context, AttributeSet)
*/
public Preference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
mContext = context;
final TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.Preference, defStyleAttr, defStyleRes);
for (int i = a.getIndexCount() - 1; i >= 0; i--) {
int attr = a.getIndex(i);
switch (attr) {
case com.android.internal.R.styleable.Preference_icon:
mIconResId = a.getResourceId(attr, 0);
break;
case com.android.internal.R.styleable.Preference_key:
mKey = a.getString(attr);
break;
case com.android.internal.R.styleable.Preference_title:
mTitleRes = a.getResourceId(attr, 0);
mTitle = a.getText(attr);
break;
case com.android.internal.R.styleable.Preference_summary:
mSummary = a.getText(attr);
break;
case com.android.internal.R.styleable.Preference_order:
mOrder = a.getInt(attr, mOrder);
break;
case com.android.internal.R.styleable.Preference_fragment:
mFragment = a.getString(attr);
break;
case com.android.internal.R.styleable.Preference_layout:
mLayoutResId = a.getResourceId(attr, mLayoutResId);
break;
case com.android.internal.R.styleable.Preference_widgetLayout:
mWidgetLayoutResId = a.getResourceId(attr, mWidgetLayoutResId);
break;
case com.android.internal.R.styleable.Preference_enabled:
mEnabled = a.getBoolean(attr, true);
break;
case com.android.internal.R.styleable.Preference_selectable:
mSelectable = a.getBoolean(attr, true);
break;
case com.android.internal.R.styleable.Preference_persistent:
mPersistent = a.getBoolean(attr, mPersistent);
break;
case com.android.internal.R.styleable.Preference_dependency:
mDependencyKey = a.getString(attr);
break;
case com.android.internal.R.styleable.Preference_defaultValue:
mDefaultValue = onGetDefaultValue(a, attr);
break;
case com.android.internal.R.styleable.Preference_shouldDisableView:
mShouldDisableView = a.getBoolean(attr, mShouldDisableView);
break;
case com.android.internal.R.styleable.Preference_recycleEnabled:
mRecycleEnabled = a.getBoolean(attr, mRecycleEnabled);
break;
case com.android.internal.R.styleable.Preference_singleLineTitle:
mSingleLineTitle = a.getBoolean(attr, mSingleLineTitle);
mHasSingleLineTitleAttr = true;
break;
case com.android.internal.R.styleable.Preference_iconSpaceReserved:
mIconSpaceReserved = a.getBoolean(attr, mIconSpaceReserved);
break;
}
}
a.recycle();
}
/**
* Perform inflation from XML and apply a class-specific base style. This
* constructor of Preference allows subclasses to use their own base style
* when they are inflating. For example, a {@link CheckBoxPreference}
* constructor calls this version of the super class constructor and
* supplies {@code android.R.attr.checkBoxPreferenceStyle} for
* <var>defStyleAttr</var>. This allows the theme's checkbox preference
* style to modify all of the base preference attributes as well as the
* {@link CheckBoxPreference} class's attributes.
*
* @param context The Context this is associated with, through which it can
* access the current theme, resources,
* {@link SharedPreferences}, etc.
* @param attrs The attributes of the XML tag that is inflating the
* preference.
* @param defStyleAttr An attribute in the current theme that contains a
* reference to a style resource that supplies default values for
* the view. Can be 0 to not look for defaults.
* @see #Preference(Context, AttributeSet)
*/
public Preference(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
/**
* Constructor that is called when inflating a Preference from XML. This is
* called when a Preference is being constructed from an XML file, supplying
* attributes that were specified in the XML file. This version uses a
* default style of 0, so the only attribute values applied are those in the
* Context's Theme and the given AttributeSet.
*
* @param context The Context this is associated with, through which it can
* access the current theme, resources, {@link SharedPreferences},
* etc.
* @param attrs The attributes of the XML tag that is inflating the
* preference.
* @see #Preference(Context, AttributeSet, int)
*/
public Preference(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.preferenceStyle);
}
/**
* Constructor to create a Preference.
*
* @param context The Context in which to store Preference values.
*/
public Preference(Context context) {
this(context, null);
}
/**
* Called when a Preference is being inflated and the default value
* attribute needs to be read. Since different Preference types have
* different value types, the subclass should get and return the default
* value which will be its value type.
* <p>
* For example, if the value type is String, the body of the method would
* proxy to {@link TypedArray#getString(int)}.
*
* @param a The set of attributes.
* @param index The index of the default value attribute.
* @return The default value of this preference type.
*/
protected Object onGetDefaultValue(TypedArray a, int index) {
return null;
}
/**
* Sets an {@link Intent} to be used for
* {@link Context#startActivity(Intent)} when this Preference is clicked.
*
* @param intent The intent associated with this Preference.
*/
public void setIntent(Intent intent) {
mIntent = intent;
}
/**
* Return the {@link Intent} associated with this Preference.
*
* @return The {@link Intent} last set via {@link #setIntent(Intent)} or XML.
*/
public Intent getIntent() {
return mIntent;
}
/**
* Sets the class name of a fragment to be shown when this Preference is clicked.
*
* @param fragment The class name of the fragment associated with this Preference.
*/
public void setFragment(String fragment) {
mFragment = fragment;
}
/**
* Return the fragment class name associated with this Preference.
*
* @return The fragment class name last set via {@link #setFragment} or XML.
*/
public String getFragment() {
return mFragment;
}
/**
* Sets a {@link PreferenceDataStore} to be used by this Preference instead of using
* {@link android.content.SharedPreferences}.
*
* <p>The data store will remain assigned even if the Preference is moved around the preference
* hierarchy. It will also override a data store propagated from the {@link PreferenceManager}
* that owns this Preference.
*
* @param dataStore The {@link PreferenceDataStore} to be used by this Preference.
* @see PreferenceManager#setPreferenceDataStore(PreferenceDataStore)
*/
public void setPreferenceDataStore(PreferenceDataStore dataStore) {
mPreferenceDataStore = dataStore;
}
/**
* Returns {@link PreferenceDataStore} used by this Preference. Returns {@code null} if
* {@link android.content.SharedPreferences} is used instead.
*
* <p>By default preferences always use {@link android.content.SharedPreferences}. To make this
* preference to use the {@link PreferenceDataStore} you need to assign your implementation
* to the Preference itself via {@link #setPreferenceDataStore(PreferenceDataStore)} or to its
* {@link PreferenceManager} via
* {@link PreferenceManager#setPreferenceDataStore(PreferenceDataStore)}.
*
* @return The {@link PreferenceDataStore} used by this Preference or {@code null} if none.
*/
@Nullable
public PreferenceDataStore getPreferenceDataStore() {
if (mPreferenceDataStore != null) {
return mPreferenceDataStore;
} else if (mPreferenceManager != null) {
return mPreferenceManager.getPreferenceDataStore();
}
return null;
}
/**
* Return the extras Bundle object associated with this preference, creating
* a new Bundle if there currently isn't one. You can use this to get and
* set individual extra key/value pairs.
*/
public Bundle getExtras() {
if (mExtras == null) {
mExtras = new Bundle();
}
return mExtras;
}
/**
* Return the extras Bundle object associated with this preference, returning {@code null} if
* there is not currently one.
*/
public Bundle peekExtras() {
return mExtras;
}
/**
* Sets the layout resource that is inflated as the {@link View} to be shown
* for this Preference. In most cases, the default layout is sufficient for
* custom Preference objects and only the widget layout needs to be changed.
* <p>
* This layout should contain a {@link ViewGroup} with ID
* {@link android.R.id#widget_frame} to be the parent of the specific widget
* for this Preference. It should similarly contain
* {@link android.R.id#title} and {@link android.R.id#summary}.
*
* @param layoutResId The layout resource ID to be inflated and returned as
* a {@link View}.
* @see #setWidgetLayoutResource(int)
*/
public void setLayoutResource(@LayoutRes int layoutResId) {
if (layoutResId != mLayoutResId) {
// Layout changed
mRecycleEnabled = false;
}
mLayoutResId = layoutResId;
}
/**
* Gets the layout resource that will be shown as the {@link View} for this Preference.
*
* @return The layout resource ID.
*/
@LayoutRes
public int getLayoutResource() {
return mLayoutResId;
}
/**
* Sets the layout for the controllable widget portion of this Preference. This
* is inflated into the main layout. For example, a {@link CheckBoxPreference}
* would specify a custom layout (consisting of just the CheckBox) here,
* instead of creating its own main layout.
*
* @param widgetLayoutResId The layout resource ID to be inflated into the
* main layout.
* @see #setLayoutResource(int)
*/
public void setWidgetLayoutResource(@LayoutRes int widgetLayoutResId) {
if (widgetLayoutResId != mWidgetLayoutResId) {
// Layout changed
mRecycleEnabled = false;
}
mWidgetLayoutResId = widgetLayoutResId;
}
/**
* Gets the layout resource for the controllable widget portion of this Preference.
*
* @return The layout resource ID.
*/
@LayoutRes
public int getWidgetLayoutResource() {
return mWidgetLayoutResId;
}
/**
* Gets the View that will be shown in the {@link PreferenceActivity}.
*
* @param convertView The old View to reuse, if possible. Note: You should
* check that this View is non-null and of an appropriate type
* before using. If it is not possible to convert this View to
* display the correct data, this method can create a new View.
* @param parent The parent that this View will eventually be attached to.
* @return Returns the same Preference object, for chaining multiple calls
* into a single statement.
* @see #onCreateView(ViewGroup)
* @see #onBindView(View)
*/
public View getView(View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = onCreateView(parent);
}
onBindView(convertView);
return convertView;
}
/**
* Creates the View to be shown for this Preference in the
* {@link PreferenceActivity}. The default behavior is to inflate the main
* layout of this Preference (see {@link #setLayoutResource(int)}. If
* changing this behavior, please specify a {@link ViewGroup} with ID
* {@link android.R.id#widget_frame}.
* <p>
* Make sure to call through to the superclass's implementation.
*
* @param parent The parent that this View will eventually be attached to.
* @return The View that displays this Preference.
* @see #onBindView(View)
*/
@CallSuper
protected View onCreateView(ViewGroup parent) {
final LayoutInflater layoutInflater =
(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = layoutInflater.inflate(mLayoutResId, parent, false);
final ViewGroup widgetFrame = (ViewGroup) layout
.findViewById(com.android.internal.R.id.widget_frame);
if (widgetFrame != null) {
if (mWidgetLayoutResId != 0) {
layoutInflater.inflate(mWidgetLayoutResId, widgetFrame);
} else {
widgetFrame.setVisibility(View.GONE);
}
}
return layout;
}
/**
* Binds the created View to the data for this Preference.
* <p>
* This is a good place to grab references to custom Views in the layout and
* set properties on them.
* <p>
* Make sure to call through to the superclass's implementation.
*
* @param view The View that shows this Preference.
* @see #onCreateView(ViewGroup)
*/
@CallSuper
protected void onBindView(View view) {
final TextView titleView = (TextView) view.findViewById(com.android.internal.R.id.title);
if (titleView != null) {
final CharSequence title = getTitle();
if (!TextUtils.isEmpty(title)) {
titleView.setText(title);
titleView.setVisibility(View.VISIBLE);
if (mHasSingleLineTitleAttr) {
titleView.setSingleLine(mSingleLineTitle);
}
} else {
titleView.setVisibility(View.GONE);
}
}
final TextView summaryView = (TextView) view.findViewById(
com.android.internal.R.id.summary);
if (summaryView != null) {
final CharSequence summary = getSummary();
if (!TextUtils.isEmpty(summary)) {
summaryView.setText(summary);
summaryView.setVisibility(View.VISIBLE);
} else {
summaryView.setVisibility(View.GONE);
}
}
final ImageView imageView = (ImageView) view.findViewById(com.android.internal.R.id.icon);
if (imageView != null) {
if (mIconResId != 0 || mIcon != null) {
if (mIcon == null) {
mIcon = getContext().getDrawable(mIconResId);
}
if (mIcon != null) {
imageView.setImageDrawable(mIcon);
}
}
if (mIcon != null) {
imageView.setVisibility(View.VISIBLE);
} else {
imageView.setVisibility(mIconSpaceReserved ? View.INVISIBLE : View.GONE);
}
}
final View imageFrame = view.findViewById(com.android.internal.R.id.icon_frame);
if (imageFrame != null) {
if (mIcon != null) {
imageFrame.setVisibility(View.VISIBLE);
} else {
imageFrame.setVisibility(mIconSpaceReserved ? View.INVISIBLE : View.GONE);
}
}
if (mShouldDisableView) {
setEnabledStateOnViews(view, isEnabled());
}
}
/**
* Makes sure the view (and any children) get the enabled state changed.
*/
private void setEnabledStateOnViews(View v, boolean enabled) {
v.setEnabled(enabled);
if (v instanceof ViewGroup) {
final ViewGroup vg = (ViewGroup) v;
for (int i = vg.getChildCount() - 1; i >= 0; i--) {
setEnabledStateOnViews(vg.getChildAt(i), enabled);
}
}
}
/**
* Sets the order of this Preference with respect to other Preference objects on the same level.
* If this is not specified, the default behavior is to sort alphabetically. The
* {@link PreferenceGroup#setOrderingAsAdded(boolean)} can be used to order Preference objects
* based on the order they appear in the XML.
*
* @param order the order for this Preference. A lower value will be shown first. Use
* {@link #DEFAULT_ORDER} to sort alphabetically or allow ordering from XML
* @see PreferenceGroup#setOrderingAsAdded(boolean)
* @see #DEFAULT_ORDER
*/
public void setOrder(int order) {
if (order != mOrder) {
mOrder = order;
// Reorder the list
notifyHierarchyChanged();
}
}
/**
* Gets the order of this Preference with respect to other Preference objects on the same level.
*
* @return the order of this Preference
* @see #setOrder(int)
*/
public int getOrder() {
return mOrder;
}
/**
* Sets the title for this Preference with a CharSequence. This title will be placed into the ID
* {@link android.R.id#title} within the View created by {@link #onCreateView(ViewGroup)}.
*
* @param title the title for this Preference
*/
public void setTitle(CharSequence title) {
if (title == null && mTitle != null || title != null && !title.equals(mTitle)) {
mTitleRes = 0;
mTitle = title;
notifyChanged();
}
}
/**
* Sets the title for this Preference with a resource ID.
*
* @see #setTitle(CharSequence)
* @param titleResId the title as a resource ID
*/
public void setTitle(@StringRes int titleResId) {
setTitle(mContext.getString(titleResId));
mTitleRes = titleResId;
}
/**
* Returns the title resource ID of this Preference. If the title did not come from a resource,
* {@code 0} is returned.
*
* @return the title resource
* @see #setTitle(int)
*/
@StringRes
public int getTitleRes() {
return mTitleRes;
}
/**
* Returns the title of this Preference.
*
* @return the title
* @see #setTitle(CharSequence)
*/
public CharSequence getTitle() {
return mTitle;
}
/**
* Sets the icon for this Preference with a Drawable. This icon will be placed into the ID
* {@link android.R.id#icon} within the View created by {@link #onCreateView(ViewGroup)}.
*
* @param icon the optional icon for this Preference
*/
public void setIcon(Drawable icon) {
if ((icon == null && mIcon != null) || (icon != null && mIcon != icon)) {
mIcon = icon;
notifyChanged();
}
}
/**
* Sets the icon for this Preference with a resource ID.
*
* @see #setIcon(Drawable)
* @param iconResId the icon as a resource ID
*/
public void setIcon(@DrawableRes int iconResId) {
if (mIconResId != iconResId) {
mIconResId = iconResId;
setIcon(mContext.getDrawable(iconResId));
}
}
/**
* Returns the icon of this Preference.
*
* @return the icon
* @see #setIcon(Drawable)
*/
public Drawable getIcon() {
if (mIcon == null && mIconResId != 0) {
mIcon = getContext().getDrawable(mIconResId);
}
return mIcon;
}
/**
* Returns the summary of this Preference.
*
* @return the summary
* @see #setSummary(CharSequence)
*/
public CharSequence getSummary() {
return mSummary;
}
/**
* Sets the summary for this Preference with a CharSequence.
*
* @param summary the summary for the preference
*/
public void setSummary(CharSequence summary) {
if (summary == null && mSummary != null || summary != null && !summary.equals(mSummary)) {
mSummary = summary;
notifyChanged();
}
}
/**
* Sets the summary for this Preference with a resource ID.
*
* @see #setSummary(CharSequence)
* @param summaryResId the summary as a resource
*/
public void setSummary(@StringRes int summaryResId) {
setSummary(mContext.getString(summaryResId));
}
/**
* Sets whether this Preference is enabled. If disabled, it will
* not handle clicks.
*
* @param enabled set {@code true} to enable it
*/
public void setEnabled(boolean enabled) {
if (mEnabled != enabled) {
mEnabled = enabled;
// Enabled state can change dependent preferences' states, so notify
notifyDependencyChange(shouldDisableDependents());
notifyChanged();
}
}
/**
* Checks whether this Preference should be enabled in the list.
*
* @return {@code true} if this Preference is enabled, false otherwise
*/
public boolean isEnabled() {
return mEnabled && mDependencyMet && mParentDependencyMet;
}
/**
* Sets whether this Preference is selectable.
*
* @param selectable set {@code true} to make it selectable
*/
public void setSelectable(boolean selectable) {
if (mSelectable != selectable) {
mSelectable = selectable;
notifyChanged();
}
}
/**
* Checks whether this Preference should be selectable in the list.
*
* @return {@code true} if it is selectable, {@code false} otherwise
*/
public boolean isSelectable() {
return mSelectable;
}
/**
* Sets whether this Preference should disable its view when it gets disabled.
*
* <p>For example, set this and {@link #setEnabled(boolean)} to false for preferences that are
* only displaying information and 1) should not be clickable 2) should not have the view set to
* the disabled state.
*
* @param shouldDisableView set {@code true} if this preference should disable its view when
* the preference is disabled
*/
public void setShouldDisableView(boolean shouldDisableView) {
mShouldDisableView = shouldDisableView;
notifyChanged();
}
/**
* Checks whether this Preference should disable its view when it's action is disabled.
*
* @see #setShouldDisableView(boolean)
* @return {@code true} if it should disable the view
*/
public boolean getShouldDisableView() {
return mShouldDisableView;
}
/**
* Sets whether this Preference has enabled to have its view recycled when used in the list
* view. By default the recycling is enabled.
*
* <p>The value can be changed only before this preference is added to the preference hierarchy.
*
* <p>If view recycling is not allowed then each time the list view populates this preference
* the {@link #getView(View, ViewGroup)} method receives a {@code null} convert view and needs
* to recreate the view. Otherwise view gets recycled and only {@link #onBindView(View)} gets
* called.
*
* @param enabled set {@code true} if this preference view should be recycled
*/
@CallSuper
public void setRecycleEnabled(boolean enabled) {
mRecycleEnabled = enabled;
notifyChanged();
}
/**
* Checks whether this Preference has enabled to have its view recycled when used in the list
* view.
*
* @see #setRecycleEnabled(boolean)
* @return {@code true} if this preference view should be recycled
*/
public boolean isRecycleEnabled() {
return mRecycleEnabled;
}
/**
* Sets whether to constrain the title of this Preference to a single line instead of
* letting it wrap onto multiple lines.
*
* @param singleLineTitle set {@code true} if the title should be constrained to one line
*/
public void setSingleLineTitle(boolean singleLineTitle) {
mHasSingleLineTitleAttr = true;
mSingleLineTitle = singleLineTitle;
notifyChanged();
}
/**
* Gets whether the title of this preference is constrained to a single line.
*
* @see #setSingleLineTitle(boolean)
* @return {@code true} if the title of this preference is constrained to a single line
*/
public boolean isSingleLineTitle() {
return mSingleLineTitle;
}
/**
* Sets whether to reserve the space of this Preference icon view when no icon is provided.
*
* @param iconSpaceReserved set {@code true} if the space for the icon view should be reserved
*/
public void setIconSpaceReserved(boolean iconSpaceReserved) {
mIconSpaceReserved = iconSpaceReserved;
notifyChanged();
}
/**
* Gets whether the space this preference icon view is reserved.
*
* @see #setIconSpaceReserved(boolean)
* @return {@code true} if the space of this preference icon view is reserved
*/
public boolean isIconSpaceReserved() {
return mIconSpaceReserved;
}
/**
* Returns a unique ID for this Preference. This ID should be unique across all
* Preference objects in a hierarchy.
*
* @return A unique ID for this Preference.
*/
@UnsupportedAppUsage
long getId() {
return mId;
}
/**
* Processes a click on the preference. This includes saving the value to
* the {@link SharedPreferences}. However, the overridden method should
* call {@link #callChangeListener(Object)} to make sure the client wants to
* update the preference's state with the new value.
*/
protected void onClick() {
}
/**
* Sets the key for this Preference, which is used as a key to the {@link SharedPreferences} or
* {@link PreferenceDataStore}. This should be unique for the package.
*
* @param key The key for the preference.
*/
public void setKey(String key) {
mKey = key;
if (mRequiresKey && !hasKey()) {
requireKey();
}
}
/**
* Gets the key for this Preference, which is also the key used for storing values into
* {@link SharedPreferences} or {@link PreferenceDataStore}.
*
* @return The key.
*/
public String getKey() {
return mKey;
}
/**
* Checks whether the key is present, and if it isn't throws an
* exception. This should be called by subclasses that persist their preferences.
*
* @throws IllegalStateException If there is no key assigned.
*/
void requireKey() {
if (mKey == null) {
throw new IllegalStateException("Preference does not have a key assigned.");
}
mRequiresKey = true;
}
/**
* Checks whether this Preference has a valid key.
*
* @return True if the key exists and is not a blank string, false otherwise.
*/
public boolean hasKey() {
return !TextUtils.isEmpty(mKey);
}
/**
* Checks whether this Preference is persistent. If it is, it stores its value(s) into
* the persistent {@link SharedPreferences} storage by default or into
* {@link PreferenceDataStore} if assigned.
*
* @return True if it is persistent.
*/
public boolean isPersistent() {
return mPersistent;
}
/**
* Checks whether, at the given time this method is called, this Preference should store/restore
* its value(s) into the {@link SharedPreferences} or into {@link PreferenceDataStore} if
* assigned. This, at minimum, checks whether this Preference is persistent and it currently has
* a key. Before you save/restore from the storage, check this first.
*
* @return True if it should persist the value.
*/
protected boolean shouldPersist() {
return mPreferenceManager != null && isPersistent() && hasKey();
}
/**
* Sets whether this Preference is persistent. When persistent, it stores its value(s) into
* the persistent {@link SharedPreferences} storage by default or into
* {@link PreferenceDataStore} if assigned.
*
* @param persistent set {@code true} if it should store its value(s) into the storage.
*/
public void setPersistent(boolean persistent) {
mPersistent = persistent;
}
/**
* Call this method after the user changes the preference, but before the
* internal state is set. This allows the client to ignore the user value.
*
* @param newValue The new value of this Preference.
* @return True if the user value should be set as the preference
* value (and persisted).
*/
protected boolean callChangeListener(Object newValue) {
return mOnChangeListener == null || mOnChangeListener.onPreferenceChange(this, newValue);
}
/**
* Sets the callback to be invoked when this Preference is changed by the
* user (but before the internal state has been updated).
*
* @param onPreferenceChangeListener The callback to be invoked.
*/
public void setOnPreferenceChangeListener(OnPreferenceChangeListener onPreferenceChangeListener) {
mOnChangeListener = onPreferenceChangeListener;
}
/**
* Returns the callback to be invoked when this Preference is changed by the
* user (but before the internal state has been updated).
*
* @return The callback to be invoked.
*/
public OnPreferenceChangeListener getOnPreferenceChangeListener() {
return mOnChangeListener;
}
/**
* Sets the callback to be invoked when this Preference is clicked.
*
* @param onPreferenceClickListener The callback to be invoked.
*/
public void setOnPreferenceClickListener(OnPreferenceClickListener onPreferenceClickListener) {
mOnClickListener = onPreferenceClickListener;
}
/**
* Returns the callback to be invoked when this Preference is clicked.
*
* @return The callback to be invoked.
*/
public OnPreferenceClickListener getOnPreferenceClickListener() {
return mOnClickListener;
}
/**
* Called when a click should be performed.
*
* @param preferenceScreen A {@link PreferenceScreen} whose hierarchy click
* listener should be called in the proper order (between other
* processing). May be {@code null}.
* @hide
*/
@UnsupportedAppUsage
public void performClick(PreferenceScreen preferenceScreen) {
if (!isEnabled()) {
return;
}
onClick();
if (mOnClickListener != null && mOnClickListener.onPreferenceClick(this)) {
return;
}
PreferenceManager preferenceManager = getPreferenceManager();
if (preferenceManager != null) {
PreferenceManager.OnPreferenceTreeClickListener listener = preferenceManager
.getOnPreferenceTreeClickListener();
if (preferenceScreen != null && listener != null
&& listener.onPreferenceTreeClick(preferenceScreen, this)) {
return;
}
}
if (mIntent != null) {
Context context = getContext();
context.startActivity(mIntent);
}
}
/**
* Allows a Preference to intercept key events without having focus.
* For example, SeekBarPreference uses this to intercept +/- to adjust
* the progress.
* @return True if the Preference handled the key. Returns false by default.
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
public boolean onKey(View v, int keyCode, KeyEvent event) {
return false;
}
/**
* Returns the {@link android.content.Context} of this Preference.
* Each Preference in a Preference hierarchy can be
* from different Context (for example, if multiple activities provide preferences into a single
* {@link PreferenceActivity}). This Context will be used to save the Preference values.
*
* @return The Context of this Preference.
*/
public Context getContext() {
return mContext;
}
/**
* Returns the {@link SharedPreferences} where this Preference can read its
* value(s). Usually, it's easier to use one of the helper read methods:
* {@link #getPersistedBoolean(boolean)}, {@link #getPersistedFloat(float)},
* {@link #getPersistedInt(int)}, {@link #getPersistedLong(long)},
* {@link #getPersistedString(String)}. To save values, see
* {@link #getEditor()}.
* <p>
* In some cases, writes to the {@link #getEditor()} will not be committed
* right away and hence not show up in the returned
* {@link SharedPreferences}, this is intended behavior to improve
* performance.
*
* @return the {@link SharedPreferences} where this Preference reads its value(s). If
* this preference isn't attached to a Preference hierarchy or if
* a {@link PreferenceDataStore} has been set, this method returns {@code null}.
* @see #getEditor()
* @see #setPreferenceDataStore(PreferenceDataStore)
*/
public SharedPreferences getSharedPreferences() {
if (mPreferenceManager == null || getPreferenceDataStore() != null) {
return null;
}
return mPreferenceManager.getSharedPreferences();
}
/**
* Returns an {@link SharedPreferences.Editor} where this Preference can
* save its value(s). Usually it's easier to use one of the helper save
* methods: {@link #persistBoolean(boolean)}, {@link #persistFloat(float)},
* {@link #persistInt(int)}, {@link #persistLong(long)},
* {@link #persistString(String)}. To read values, see
* {@link #getSharedPreferences()}. If {@link #shouldCommit()} returns
* true, it is this Preference's responsibility to commit.
* <p>
* In some cases, writes to this will not be committed right away and hence
* not show up in the SharedPreferences, this is intended behavior to
* improve performance.
*
* @return a {@link SharedPreferences.Editor} where this preference saves its value(s). If
* this preference isn't attached to a Preference hierarchy or if
* a {@link PreferenceDataStore} has been set, this method returns {@code null}.
* @see #shouldCommit()
* @see #getSharedPreferences()
* @see #setPreferenceDataStore(PreferenceDataStore)
*/
public SharedPreferences.Editor getEditor() {
if (mPreferenceManager == null || getPreferenceDataStore() != null) {
return null;
}
return mPreferenceManager.getEditor();
}
/**
* Returns whether the {@link Preference} should commit its saved value(s) in
* {@link #getEditor()}. This may return false in situations where batch
* committing is being done (by the manager) to improve performance.
*
* <p>If this preference is using {@link PreferenceDataStore} this value is irrelevant.
*
* @return Whether the Preference should commit its saved value(s).
* @see #getEditor()
*/
public boolean shouldCommit() {
if (mPreferenceManager == null) {
return false;
}
return mPreferenceManager.shouldCommit();
}
/**
* Compares Preference objects based on order (if set), otherwise alphabetically on the titles.
*
* @param another The Preference to compare to this one.
* @return 0 if the same; less than 0 if this Preference sorts ahead of <var>another</var>;
* greater than 0 if this Preference sorts after <var>another</var>.
*/
@Override
public int compareTo(Preference another) {
if (mOrder != another.mOrder) {
// Do order comparison
return mOrder - another.mOrder;
} else if (mTitle == another.mTitle) {
// If titles are null or share same object comparison
return 0;
} else if (mTitle == null) {
return 1;
} else if (another.mTitle == null) {
return -1;
} else {
// Do name comparison
return CharSequences.compareToIgnoreCase(mTitle, another.mTitle);
}
}
/**
* Sets the internal change listener.
*
* @param listener The listener.
* @see #notifyChanged()
*/
@UnsupportedAppUsage
final void setOnPreferenceChangeInternalListener(OnPreferenceChangeInternalListener listener) {
mListener = listener;
}
/**
* Should be called when the data of this {@link Preference} has changed.
*/
protected void notifyChanged() {
if (mListener != null) {
mListener.onPreferenceChange(this);
}
}
/**
* Should be called when a Preference has been
* added/removed from this group, or the ordering should be
* re-evaluated.
*/
protected void notifyHierarchyChanged() {
if (mListener != null) {
mListener.onPreferenceHierarchyChange(this);
}
}
/**
* Gets the {@link PreferenceManager} that manages this Preference object's tree.
*
* @return The {@link PreferenceManager}.
*/
public PreferenceManager getPreferenceManager() {
return mPreferenceManager;
}
/**
* Called when this Preference has been attached to a Preference hierarchy.
* Make sure to call the super implementation.
*
* @param preferenceManager The PreferenceManager of the hierarchy.
*/
protected void onAttachedToHierarchy(PreferenceManager preferenceManager) {
mPreferenceManager = preferenceManager;
mId = preferenceManager.getNextId();
dispatchSetInitialValue();
}
/**
* Called when the Preference hierarchy has been attached to the
* {@link PreferenceActivity}. This can also be called when this
* Preference has been attached to a group that was already attached
* to the {@link PreferenceActivity}.
*/
protected void onAttachedToActivity() {
// At this point, the hierarchy that this preference is in is connected
// with all other preferences.
registerDependency();
}
/**
* Assigns a {@link PreferenceGroup} as the parent of this Preference. Set {@code null} to
* remove the current parent.
*
* @param parentGroup Parent preference group of this Preference or {@code null} if none.
*/
void assignParent(@Nullable PreferenceGroup parentGroup) {
mParentGroup = parentGroup;
}
private void registerDependency() {
if (TextUtils.isEmpty(mDependencyKey)) return;
Preference preference = findPreferenceInHierarchy(mDependencyKey);
if (preference != null) {
preference.registerDependent(this);
} else {
throw new IllegalStateException("Dependency \"" + mDependencyKey
+ "\" not found for preference \"" + mKey + "\" (title: \"" + mTitle + "\"");
}
}
private void unregisterDependency() {
if (mDependencyKey != null) {
final Preference oldDependency = findPreferenceInHierarchy(mDependencyKey);
if (oldDependency != null) {
oldDependency.unregisterDependent(this);
}
}
}
/**
* Finds a Preference in this hierarchy (the whole thing,
* even above/below your {@link PreferenceScreen} screen break) with the given
* key.
* <p>
* This only functions after we have been attached to a hierarchy.
*
* @param key The key of the Preference to find.
* @return The Preference that uses the given key.
*/
protected Preference findPreferenceInHierarchy(String key) {
if (TextUtils.isEmpty(key) || mPreferenceManager == null) {
return null;
}
return mPreferenceManager.findPreference(key);
}
/**
* Adds a dependent Preference on this Preference so we can notify it.
* Usually, the dependent Preference registers itself (it's good for it to
* know it depends on something), so please use
* {@link Preference#setDependency(String)} on the dependent Preference.
*
* @param dependent The dependent Preference that will be enabled/disabled
* according to the state of this Preference.
*/
@UnsupportedAppUsage
private void registerDependent(Preference dependent) {
if (mDependents == null) {
mDependents = new ArrayList<Preference>();
}
mDependents.add(dependent);
dependent.onDependencyChanged(this, shouldDisableDependents());
}
/**
* Removes a dependent Preference on this Preference.
*
* @param dependent The dependent Preference that will be enabled/disabled
* according to the state of this Preference.
* @return Returns the same Preference object, for chaining multiple calls
* into a single statement.
*/
private void unregisterDependent(Preference dependent) {
if (mDependents != null) {
mDependents.remove(dependent);
}
}
/**
* Notifies any listening dependents of a change that affects the
* dependency.
*
* @param disableDependents Whether this Preference should disable
* its dependents.
*/
public void notifyDependencyChange(boolean disableDependents) {
final List<Preference> dependents = mDependents;
if (dependents == null) {
return;
}
final int dependentsCount = dependents.size();
for (int i = 0; i < dependentsCount; i++) {
dependents.get(i).onDependencyChanged(this, disableDependents);
}
}
/**
* Called when the dependency changes.
*
* @param dependency The Preference that this Preference depends on.
* @param disableDependent Set true to disable this Preference.
*/
public void onDependencyChanged(Preference dependency, boolean disableDependent) {
if (mDependencyMet == disableDependent) {
mDependencyMet = !disableDependent;
// Enabled state can change dependent preferences' states, so notify
notifyDependencyChange(shouldDisableDependents());
notifyChanged();
}
}
/**
* Called when the implicit parent dependency changes.
*
* @param parent The Preference that this Preference depends on.
* @param disableChild Set true to disable this Preference.
*/
public void onParentChanged(Preference parent, boolean disableChild) {
if (mParentDependencyMet == disableChild) {
mParentDependencyMet = !disableChild;
// Enabled state can change dependent preferences' states, so notify
notifyDependencyChange(shouldDisableDependents());
notifyChanged();
}
}
/**
* Checks whether this preference's dependents should currently be
* disabled.
*
* @return True if the dependents should be disabled, otherwise false.
*/
public boolean shouldDisableDependents() {
return !isEnabled();
}
/**
* Sets the key of a Preference that this Preference will depend on. If that
* Preference is not set or is off, this Preference will be disabled.
*
* @param dependencyKey The key of the Preference that this depends on.
*/
public void setDependency(String dependencyKey) {
// Unregister the old dependency, if we had one
unregisterDependency();
// Register the new
mDependencyKey = dependencyKey;
registerDependency();
}
/**
* Returns the key of the dependency on this Preference.
*
* @return The key of the dependency.
* @see #setDependency(String)
*/
public String getDependency() {
return mDependencyKey;
}
/**
* Returns the {@link PreferenceGroup} which is this Preference assigned to or {@code null} if
* this preference is not assigned to any group or is a root Preference.
*
* @return the parent PreferenceGroup or {@code null} if not attached to any
*/
@Nullable
public PreferenceGroup getParent() {
return mParentGroup;
}
/**
* Called when this Preference is being removed from the hierarchy. You
* should remove any references to this Preference that you know about. Make
* sure to call through to the superclass implementation.
*/
@CallSuper
protected void onPrepareForRemoval() {
unregisterDependency();
}
/**
* Sets the default value for this Preference, which will be set either if
* persistence is off or persistence is on and the preference is not found
* in the persistent storage.
*
* @param defaultValue The default value.
*/
public void setDefaultValue(Object defaultValue) {
mDefaultValue = defaultValue;
}
private void dispatchSetInitialValue() {
if (getPreferenceDataStore() != null) {
onSetInitialValue(true, mDefaultValue);
return;
}
// By now, we know if we are persistent.
final boolean shouldPersist = shouldPersist();
if (!shouldPersist || !getSharedPreferences().contains(mKey)) {
if (mDefaultValue != null) {
onSetInitialValue(false, mDefaultValue);
}
} else {
onSetInitialValue(true, null);
}
}
/**
* Implement this to set the initial value of the Preference.
*
* <p>If <var>restorePersistedValue</var> is true, you should restore the
* Preference value from the {@link android.content.SharedPreferences}. If
* <var>restorePersistedValue</var> is false, you should set the Preference
* value to defaultValue that is given (and possibly store to SharedPreferences
* if {@link #shouldPersist()} is true).
*
* <p>In case of using {@link PreferenceDataStore}, the <var>restorePersistedValue</var> is
* always {@code true}. But the default value (if provided) is set.
*
* <p>This may not always be called. One example is if it should not persist
* but there is no default value given.
*
* @param restorePersistedValue True to restore the persisted value;
* false to use the given <var>defaultValue</var>.
* @param defaultValue The default value for this Preference. Only use this
* if <var>restorePersistedValue</var> is false.
*/
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
}
private void tryCommit(SharedPreferences.Editor editor) {
if (mPreferenceManager.shouldCommit()) {
try {
editor.apply();
} catch (AbstractMethodError unused) {
// The app injected its own pre-Gingerbread
// SharedPreferences.Editor implementation without
// an apply method.
editor.commit();
}
}
}
/**
* Attempts to persist a String if this Preference is persistent.
*
* @param value The value to persist.
* @return True if this Preference is persistent. (This is not whether the
* value was persisted, since we may not necessarily commit if there
* will be a batch commit later.)
* @see #getPersistedString(String)
*/
protected boolean persistString(String value) {
if (!shouldPersist()) {
return false;
}
// Shouldn't store null
if (TextUtils.equals(value, getPersistedString(null))) {
// It's already there, so the same as persisting
return true;
}
PreferenceDataStore dataStore = getPreferenceDataStore();
if (dataStore != null) {
dataStore.putString(mKey, value);
} else {
SharedPreferences.Editor editor = mPreferenceManager.getEditor();
editor.putString(mKey, value);
tryCommit(editor);
}
return true;
}
/**
* Attempts to get a persisted String if this Preference is persistent.
*
* @param defaultReturnValue The default value to return if either this
* Preference is not persistent or this Preference is not present.
* @return The value from the data store or the default return
* value.
* @see #persistString(String)
*/
protected String getPersistedString(String defaultReturnValue) {
if (!shouldPersist()) {
return defaultReturnValue;
}
PreferenceDataStore dataStore = getPreferenceDataStore();
if (dataStore != null) {
return dataStore.getString(mKey, defaultReturnValue);
}
return mPreferenceManager.getSharedPreferences().getString(mKey, defaultReturnValue);
}
/**
* Attempts to persist a set of Strings if this Preference is persistent.
*
* @param values The values to persist.
* @return True if this Preference is persistent. (This is not whether the
* value was persisted, since we may not necessarily commit if there
* will be a batch commit later.)
* @see #getPersistedStringSet(Set)
*/
public boolean persistStringSet(Set<String> values) {
if (!shouldPersist()) {
return false;
}
// Shouldn't store null
if (values.equals(getPersistedStringSet(null))) {
// It's already there, so the same as persisting
return true;
}
PreferenceDataStore dataStore = getPreferenceDataStore();
if (dataStore != null) {
dataStore.putStringSet(mKey, values);
} else {
SharedPreferences.Editor editor = mPreferenceManager.getEditor();
editor.putStringSet(mKey, values);
tryCommit(editor);
}
return true;
}
/**
* Attempts to get a persisted set of Strings if this Preference is persistent.
*
* @param defaultReturnValue The default value to return if either this
* Preference is not persistent or this Preference is not present.
* @return The value from the data store or the default return
* value.
* @see #persistStringSet(Set)
*/
public Set<String> getPersistedStringSet(Set<String> defaultReturnValue) {
if (!shouldPersist()) {
return defaultReturnValue;
}
PreferenceDataStore dataStore = getPreferenceDataStore();
if (dataStore != null) {
return dataStore.getStringSet(mKey, defaultReturnValue);
}
return mPreferenceManager.getSharedPreferences().getStringSet(mKey, defaultReturnValue);
}
/**
* Attempts to persist an int if this Preference is persistent.
*
* @param value The value to persist.
* @return True if this Preference is persistent. (This is not whether the
* value was persisted, since we may not necessarily commit if there
* will be a batch commit later.)
* @see #persistString(String)
* @see #getPersistedInt(int)
*/
protected boolean persistInt(int value) {
if (!shouldPersist()) {
return false;
}
if (value == getPersistedInt(~value)) {
// It's already there, so the same as persisting
return true;
}
PreferenceDataStore dataStore = getPreferenceDataStore();
if (dataStore != null) {
dataStore.putInt(mKey, value);
} else {
SharedPreferences.Editor editor = mPreferenceManager.getEditor();
editor.putInt(mKey, value);
tryCommit(editor);
}
return true;
}
/**
* Attempts to get a persisted int if this Preference is persistent.
*
* @param defaultReturnValue The default value to return if either this
* Preference is not persistent or this Preference is not present.
* @return The value from the data store or the default return
* value.
* @see #getPersistedString(String)
* @see #persistInt(int)
*/
protected int getPersistedInt(int defaultReturnValue) {
if (!shouldPersist()) {
return defaultReturnValue;
}
PreferenceDataStore dataStore = getPreferenceDataStore();
if (dataStore != null) {
return dataStore.getInt(mKey, defaultReturnValue);
}
return mPreferenceManager.getSharedPreferences().getInt(mKey, defaultReturnValue);
}
/**
* Attempts to persist a long if this Preference is persistent.
*
* @param value The value to persist.
* @return True if this Preference is persistent. (This is not whether the
* value was persisted, since we may not necessarily commit if there
* will be a batch commit later.)
* @see #persistString(String)
* @see #getPersistedFloat(float)
*/
protected boolean persistFloat(float value) {
if (!shouldPersist()) {
return false;
}
if (value == getPersistedFloat(Float.NaN)) {
// It's already there, so the same as persisting
return true;
}
PreferenceDataStore dataStore = getPreferenceDataStore();
if (dataStore != null) {
dataStore.putFloat(mKey, value);
} else {
SharedPreferences.Editor editor = mPreferenceManager.getEditor();
editor.putFloat(mKey, value);
tryCommit(editor);
}
return true;
}
/**
* Attempts to get a persisted float if this Preference is persistent.
*
* @param defaultReturnValue The default value to return if either this
* Preference is not persistent or this Preference is not present.
* @return The value from the data store or the default return
* value.
* @see #getPersistedString(String)
* @see #persistFloat(float)
*/
protected float getPersistedFloat(float defaultReturnValue) {
if (!shouldPersist()) {
return defaultReturnValue;
}
PreferenceDataStore dataStore = getPreferenceDataStore();
if (dataStore != null) {
return dataStore.getFloat(mKey, defaultReturnValue);
}
return mPreferenceManager.getSharedPreferences().getFloat(mKey, defaultReturnValue);
}
/**
* Attempts to persist a long if this Preference is persistent.
*
* @param value The value to persist.
* @return True if this Preference is persistent. (This is not whether the
* value was persisted, since we may not necessarily commit if there
* will be a batch commit later.)
* @see #persistString(String)
* @see #getPersistedLong(long)
*/
protected boolean persistLong(long value) {
if (!shouldPersist()) {
return false;
}
if (value == getPersistedLong(~value)) {
// It's already there, so the same as persisting
return true;
}
PreferenceDataStore dataStore = getPreferenceDataStore();
if (dataStore != null) {
dataStore.putLong(mKey, value);
} else {
SharedPreferences.Editor editor = mPreferenceManager.getEditor();
editor.putLong(mKey, value);
tryCommit(editor);
}
return true;
}
/**
* Attempts to get a persisted long if this Preference is persistent.
*
* @param defaultReturnValue The default value to return if either this
* Preference is not persistent or this Preference is not present.
* @return The value from the data store or the default return
* value.
* @see #getPersistedString(String)
* @see #persistLong(long)
*/
protected long getPersistedLong(long defaultReturnValue) {
if (!shouldPersist()) {
return defaultReturnValue;
}
PreferenceDataStore dataStore = getPreferenceDataStore();
if (dataStore != null) {
return dataStore.getLong(mKey, defaultReturnValue);
}
return mPreferenceManager.getSharedPreferences().getLong(mKey, defaultReturnValue);
}
/**
* Attempts to persist a boolean if this Preference is persistent.
*
* @param value The value to persist.
* @return True if this Preference is persistent. (This is not whether the
* value was persisted, since we may not necessarily commit if there
* will be a batch commit later.)
* @see #persistString(String)
* @see #getPersistedBoolean(boolean)
*/
protected boolean persistBoolean(boolean value) {
if (!shouldPersist()) {
return false;
}
if (value == getPersistedBoolean(!value)) {
// It's already there, so the same as persisting
return true;
}
PreferenceDataStore dataStore = getPreferenceDataStore();
if (dataStore != null) {
dataStore.putBoolean(mKey, value);
} else {
SharedPreferences.Editor editor = mPreferenceManager.getEditor();
editor.putBoolean(mKey, value);
tryCommit(editor);
}
return true;
}
/**
* Attempts to get a persisted boolean if this Preference is persistent.
*
* @param defaultReturnValue The default value to return if either this
* Preference is not persistent or this Preference is not present.
* @return The value from the data store or the default return
* value.
* @see #getPersistedString(String)
* @see #persistBoolean(boolean)
*/
protected boolean getPersistedBoolean(boolean defaultReturnValue) {
if (!shouldPersist()) {
return defaultReturnValue;
}
PreferenceDataStore dataStore = getPreferenceDataStore();
if (dataStore != null) {
return dataStore.getBoolean(mKey, defaultReturnValue);
}
return mPreferenceManager.getSharedPreferences().getBoolean(mKey, defaultReturnValue);
}
@Override
public String toString() {
return getFilterableStringBuilder().toString();
}
/**
* Returns the text that will be used to filter this Preference depending on
* user input.
* <p>
* If overridding and calling through to the superclass, make sure to prepend
* your additions with a space.
*
* @return Text as a {@link StringBuilder} that will be used to filter this
* preference. By default, this is the title and summary
* (concatenated with a space).
*/
StringBuilder getFilterableStringBuilder() {
StringBuilder sb = new StringBuilder();
CharSequence title = getTitle();
if (!TextUtils.isEmpty(title)) {
sb.append(title).append(' ');
}
CharSequence summary = getSummary();
if (!TextUtils.isEmpty(summary)) {
sb.append(summary).append(' ');
}
if (sb.length() > 0) {
// Drop the last space
sb.setLength(sb.length() - 1);
}
return sb;
}
/**
* Store this Preference hierarchy's frozen state into the given container.
*
* @param container The Bundle in which to save the instance of this Preference.
*
* @see #restoreHierarchyState
* @see #onSaveInstanceState
*/
public void saveHierarchyState(Bundle container) {
dispatchSaveInstanceState(container);
}
/**
* Called by {@link #saveHierarchyState} to store the instance for this Preference and its
* children. May be overridden to modify how the save happens for children. For example, some
* Preference objects may want to not store an instance for their children.
*
* @param container The Bundle in which to save the instance of this Preference.
*
* @see #saveHierarchyState
* @see #onSaveInstanceState
*/
void dispatchSaveInstanceState(Bundle container) {
if (hasKey()) {
mBaseMethodCalled = false;
Parcelable state = onSaveInstanceState();
if (!mBaseMethodCalled) {
throw new IllegalStateException(
"Derived class did not call super.onSaveInstanceState()");
}
if (state != null) {
container.putParcelable(mKey, state);
}
}
}
/**
* Hook allowing a Preference to generate a representation of its internal
* state that can later be used to create a new instance with that same
* state. This state should only contain information that is not persistent
* or can be reconstructed later.
*
* @return A Parcelable object containing the current dynamic state of this Preference, or
* {@code null} if there is nothing interesting to save. The default implementation
* returns {@code null}.
* @see #onRestoreInstanceState
* @see #saveHierarchyState
*/
protected Parcelable onSaveInstanceState() {
mBaseMethodCalled = true;
return BaseSavedState.EMPTY_STATE;
}
/**
* Restore this Preference hierarchy's previously saved state from the given container.
*
* @param container The Bundle that holds the previously saved state.
*
* @see #saveHierarchyState
* @see #onRestoreInstanceState
*/
public void restoreHierarchyState(Bundle container) {
dispatchRestoreInstanceState(container);
}
/**
* Called by {@link #restoreHierarchyState} to retrieve the saved state for this
* Preference and its children. May be overridden to modify how restoring
* happens to the children of a Preference. For example, some Preference objects may
* not want to save state for their children.
*
* @param container The Bundle that holds the previously saved state.
* @see #restoreHierarchyState
* @see #onRestoreInstanceState
*/
void dispatchRestoreInstanceState(Bundle container) {
if (hasKey()) {
Parcelable state = container.getParcelable(mKey);
if (state != null) {
mBaseMethodCalled = false;
onRestoreInstanceState(state);
if (!mBaseMethodCalled) {
throw new IllegalStateException(
"Derived class did not call super.onRestoreInstanceState()");
}
}
}
}
/**
* Hook allowing a Preference to re-apply a representation of its internal state that had
* previously been generated by {@link #onSaveInstanceState}. This function will never be called
* with a {@code null} state.
*
* @param state The saved state that had previously been returned by
* {@link #onSaveInstanceState}.
* @see #onSaveInstanceState
* @see #restoreHierarchyState
*/
protected void onRestoreInstanceState(Parcelable state) {
mBaseMethodCalled = true;
if (state != BaseSavedState.EMPTY_STATE && state != null) {
throw new IllegalArgumentException("Wrong state class -- expecting Preference State");
}
}
/**
* A base class for managing the instance state of a {@link Preference}.
*
* @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 class BaseSavedState extends AbsSavedState {
public BaseSavedState(Parcel source) {
super(source);
}
public BaseSavedState(Parcelable superState) {
super(superState);
}
public static final @android.annotation.NonNull Parcelable.Creator<BaseSavedState> CREATOR =
new Parcelable.Creator<BaseSavedState>() {
public BaseSavedState createFromParcel(Parcel in) {
return new BaseSavedState(in);
}
public BaseSavedState[] newArray(int size) {
return new BaseSavedState[size];
}
};
}
}
|