实例介绍
【实例截图】
【核心代码】
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 | /* * Copyright (C) 2010 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 * * * 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 net.simonvt.calendarview; import android.app.Service; import android.content.Context; import android.content.res.Configuration; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.util.TypedValue; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; /** * This class is a calendar widget for displaying and selecting dates. The range * of dates supported by this calendar is configurable. A user can select a date * by taping on it and can scroll and fling the calendar to a desired date. * * @attr ref android.R.styleable#CalendarView_showWeekNumber * @attr ref android.R.styleable#CalendarView_firstDayOfWeek * @attr ref android.R.styleable#CalendarView_minDate * @attr ref android.R.styleable#CalendarView_maxDate * @attr ref android.R.styleable#CalendarView_shownWeekCount * @attr ref android.R.styleable#CalendarView_selectedWeekBackgroundColor * @attr ref android.R.styleable#CalendarView_focusedMonthDateColor * @attr ref android.R.styleable#CalendarView_unfocusedMonthDateColor * @attr ref android.R.styleable#CalendarView_weekNumberColor * @attr ref android.R.styleable#CalendarView_weekSeparatorLineColor * @attr ref android.R.styleable#CalendarView_selectedDateVerticalBar * @attr ref android.R.styleable#CalendarView_weekDayTextAppearance * @attr ref android.R.styleable#CalendarView_dateTextAppearance */ //@Widget public class CalendarView extends FrameLayout { /** * Tag for logging. */ private static final String LOG_TAG = CalendarView.class.getSimpleName(); /** * Default value whether to show week number. */ private static final boolean DEFAULT_SHOW_WEEK_NUMBER = true; /** * The number of milliseconds in a day.e */ private static final long MILLIS_IN_DAY = 86400000L; /** * The number of day in a week. */ private static final int DAYS_PER_WEEK = 7; /** * The number of milliseconds in a week. */ private static final long MILLIS_IN_WEEK = DAYS_PER_WEEK * MILLIS_IN_DAY; /** * Affects when the month selection will change while scrolling upe */ private static final int SCROLL_HYST_WEEKS = 2; /** * How long the GoTo fling animation should last. */ private static final int GOTO_SCROLL_DURATION = 1000; /** * The duration of the adjustment upon a user scroll in milliseconds. */ private static final int ADJUSTMENT_SCROLL_DURATION = 500; /** * How long to wait after receiving an onScrollStateChanged notification * before acting on it. */ private static final int SCROLL_CHANGE_DELAY = 40; /** * String for parsing dates. */ private static final String DATE_FORMAT = "MM/dd/yyyy"; /** * The default minimal date. */ private static final String DEFAULT_MIN_DATE = "01/01/1900"; /** * The default maximal date. */ private static final String DEFAULT_MAX_DATE = "01/01/2100"; private static final int DEFAULT_SHOWN_WEEK_COUNT = 6; private static final int DEFAULT_DATE_TEXT_SIZE = 14; private static final int UNSCALED_SELECTED_DATE_VERTICAL_BAR_WIDTH = 6; private static final int UNSCALED_WEEK_MIN_VISIBLE_HEIGHT = 12; private static final int UNSCALED_LIST_SCROLL_TOP_OFFSET = 2; private static final int UNSCALED_BOTTOM_BUFFER = 20; private static final int UNSCALED_WEEK_SEPARATOR_LINE_WIDTH = 1; private static final int DEFAULT_WEEK_DAY_TEXT_APPEARANCE_RES_ID = -1; private final int mWeekSeperatorLineWidth; private int mDateTextSize; private Drawable mSelectedDateVerticalBar; private final int mSelectedDateVerticalBarWidth; private int mSelectedWeekBackgroundColor; private int mFocusedMonthDateColor; private int mUnfocusedMonthDateColor; private int mWeekSeparatorLineColor; private int mWeekNumberColor; private int mWeekDayTextAppearanceResId; private int mDateTextAppearanceResId; /** * The top offset of the weeks list. */ private int mListScrollTopOffset = 2; /** * The visible height of a week view. */ private int mWeekMinVisibleHeight = 12; /** * The visible height of a week view. */ private int mBottomBuffer = 20; /** * The number of shown weeks. */ private int mShownWeekCount; /** * Flag whether to show the week number. */ private boolean mShowWeekNumber; /** * The number of day per week to be shown. */ private int mDaysPerWeek = 7; /** * The friction of the week list while flinging. */ private float mFriction = .05f; /** * Scale for adjusting velocity of the week list while flinging. */ private float mVelocityScale = 0.333f; /** * The adapter for the weeks list. */ private WeeksAdapter mAdapter; /** * The weeks list. */ private ListView mListView; /** * The name of the month to display. */ private TextView mMonthName; /** * The header with week day names. */ private ViewGroup mDayNamesHeader; /** * Cached labels for the week names header. */ private String[] mDayLabels; /** * The first day of the week. */ private int mFirstDayOfWeek; /** * Which month should be displayed/highlighted [0-11]. */ private int mCurrentMonthDisplayed; /** * Used for tracking during a scroll. */ private long mPreviousScrollPosition; /** * Used for tracking which direction the view is scrolling. */ private boolean mIsScrollingUp = false; /** * The previous scroll state of the weeks ListView. */ private int mPreviousScrollState = OnScrollListener.SCROLL_STATE_IDLE; /** * The current scroll state of the weeks ListView. */ private int mCurrentScrollState = OnScrollListener.SCROLL_STATE_IDLE; /** * Listener for changes in the selected day. */ private OnDateChangeListener mOnDateChangeListener; /** * Command for adjusting the position after a scroll/fling. */ private ScrollStateRunnable mScrollStateChangedRunnable = new ScrollStateRunnable(); /** * Temporary instance to avoid multiple instantiations. */ private Calendar mTempDate; /** * The first day of the focused month. */ private Calendar mFirstDayOfMonth; /** * The start date of the range supported by this picker. */ private Calendar mMinDate; /** * The end date of the range supported by this picker. */ private Calendar mMaxDate; /** * Date format for parsing dates. */ private final java.text.DateFormat mDateFormat = new SimpleDateFormat(DATE_FORMAT); /** * The current locale. */ private Locale mCurrentLocale; /** * The callback used to indicate the user changes the date. */ public interface OnDateChangeListener { /** * Called upon change of the selected day. * * @param view The view associated with this listener. * @param year The year that was set. * @param month The month that was set [0-11]. * @param dayOfMonth The day of the month that was set. */ public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth); } public CalendarView(Context context) { this(context, null); } public CalendarView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CalendarView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, 0); // initialization based on locale setCurrentLocale(Locale.getDefault()); TypedArray attributesArray = context.obtainStyledAttributes(attrs, R.styleable.CalendarView, R.attr.calendarViewStyle, 0); mShowWeekNumber = attributesArray.getBoolean(R.styleable.CalendarView_cv_showWeekNumber, DEFAULT_SHOW_WEEK_NUMBER); mFirstDayOfWeek = attributesArray.getInt(R.styleable.CalendarView_cv_firstDayOfWeek, //LocaleData.get(Locale.getDefault()).firstDayOfWeek); Calendar.getInstance().getFirstDayOfWeek()); String minDate = attributesArray.getString(R.styleable.CalendarView_cv_minDate); if (TextUtils.isEmpty(minDate) || !parseDate(minDate, mMinDate)) { parseDate(DEFAULT_MIN_DATE, mMinDate); } String maxDate = attributesArray.getString(R.styleable.CalendarView_cv_maxDate); if (TextUtils.isEmpty(maxDate) || !parseDate(maxDate, mMaxDate)) { parseDate(DEFAULT_MAX_DATE, mMaxDate); } if (mMaxDate.before(mMinDate)) { throw new IllegalArgumentException("Max date cannot be before min date."); } mShownWeekCount = attributesArray.getInt(R.styleable.CalendarView_cv_shownWeekCount, DEFAULT_SHOWN_WEEK_COUNT); mSelectedWeekBackgroundColor = attributesArray.getColor( R.styleable.CalendarView_cv_selectedWeekBackgroundColor, 0); mFocusedMonthDateColor = attributesArray.getColor( R.styleable.CalendarView_cv_focusedMonthDateColor, 0); mUnfocusedMonthDateColor = attributesArray.getColor( R.styleable.CalendarView_cv_unfocusedMonthDateColor, 0); mWeekSeparatorLineColor = attributesArray.getColor( R.styleable.CalendarView_cv_weekSeparatorLineColor, 0); mWeekNumberColor = attributesArray.getColor(R.styleable.CalendarView_cv_weekNumberColor, 0); mSelectedDateVerticalBar = attributesArray.getDrawable( R.styleable.CalendarView_cv_selectedDateVerticalBar); mDateTextAppearanceResId = attributesArray.getResourceId( R.styleable.CalendarView_cv_dateTextAppearance, android.R.style.TextAppearance_Small); updateDateTextSize(); mWeekDayTextAppearanceResId = attributesArray.getResourceId( R.styleable.CalendarView_cv_weekDayTextAppearance, DEFAULT_WEEK_DAY_TEXT_APPEARANCE_RES_ID); final Drawable horizontalDivider = attributesArray.getDrawable(R.styleable.CalendarView_cv_dividerHorizontal); attributesArray.recycle(); DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); mWeekMinVisibleHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, UNSCALED_WEEK_MIN_VISIBLE_HEIGHT, displayMetrics); mListScrollTopOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, UNSCALED_LIST_SCROLL_TOP_OFFSET, displayMetrics); mBottomBuffer = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, UNSCALED_BOTTOM_BUFFER, displayMetrics); mSelectedDateVerticalBarWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, UNSCALED_SELECTED_DATE_VERTICAL_BAR_WIDTH, displayMetrics); mWeekSeperatorLineWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, UNSCALED_WEEK_SEPARATOR_LINE_WIDTH, displayMetrics); LayoutInflater layoutInflater = (LayoutInflater) context .getSystemService(Service.LAYOUT_INFLATER_SERVICE); View content = layoutInflater.inflate(R.layout.calendar_view, null, false); addView(content); mListView = (ListView) findViewById(android.R.id.list); mDayNamesHeader = (ViewGroup) content.findViewById(R.id.cv_day_names); mMonthName = (TextView) content.findViewById(R.id.cv_month_name); ((ImageView) findViewById(R.id.cv_divider)).setImageDrawable(horizontalDivider); setUpHeader(); setUpListView(); setUpAdapter(); // go to today or whichever is close to today min or max date mTempDate.setTimeInMillis(System.currentTimeMillis()); if (mTempDate.before(mMinDate)) { goTo(mMinDate, false, true, true); } else if (mMaxDate.before(mTempDate)) { goTo(mMaxDate, false, true, true); } else { goTo(mTempDate, false, true, true); } invalidate(); } /** * Sets the number of weeks to be shown. * * @param count The shown week count. * * @attr ref android.R.styleable#CalendarView_shownWeekCount */ public void setShownWeekCount(int count) { if (mShownWeekCount != count) { mShownWeekCount = count; invalidate(); } } /** * Gets the number of weeks to be shown. * * @return The shown week count. * * @attr ref android.R.styleable#CalendarView_shownWeekCount */ public int getShownWeekCount() { return mShownWeekCount; } /** * Sets the background color for the selected week. * * @param color The week background color. * * @attr ref android.R.styleable#CalendarView_selectedWeekBackgroundColor */ public void setSelectedWeekBackgroundColor(int color) { if (mSelectedWeekBackgroundColor != color) { mSelectedWeekBackgroundColor = color; final int childCount = mListView.getChildCount(); for (int i = 0; i < childCount; i ) { WeekView weekView = (WeekView) mListView.getChildAt(i); if (weekView.mHasSelectedDay) { weekView.invalidate(); } } } } /** * Gets the background color for the selected week. * * @return The week background color. * * @attr ref android.R.styleable#CalendarView_selectedWeekBackgroundColor */ public int getSelectedWeekBackgroundColor() { return mSelectedWeekBackgroundColor; } /** * Sets the color for the dates of the focused month. * * @param color The focused month date color. * * @attr ref android.R.styleable#CalendarView_focusedMonthDateColor */ public void setFocusedMonthDateColor(int color) { if (mFocusedMonthDateColor != color) { mFocusedMonthDateColor = color; final int childCount = mListView.getChildCount(); for (int i = 0; i < childCount; i ) { WeekView weekView = (WeekView) mListView.getChildAt(i); if (weekView.mHasFocusedDay) { weekView.invalidate(); } } } } /** * Gets the color for the dates in the focused month. * * @return The focused month date color. * * @attr ref android.R.styleable#CalendarView_focusedMonthDateColor */ public int getFocusedMonthDateColor() { return mFocusedMonthDateColor; } /** * Sets the color for the dates of a not focused month. * * @param color A not focused month date color. * * @attr ref android.R.styleable#CalendarView_unfocusedMonthDateColor */ public void setUnfocusedMonthDateColor(int color) { if (mUnfocusedMonthDateColor != color) { mUnfocusedMonthDateColor = color; final int childCount = mListView.getChildCount(); for (int i = 0; i < childCount; i ) { WeekView weekView = (WeekView) mListView.getChildAt(i); if (weekView.mHasUnfocusedDay) { weekView.invalidate(); } } } } /** * Gets the color for the dates in a not focused month. * * @return A not focused month date color. * * @attr ref android.R.styleable#CalendarView_unfocusedMonthDateColor */ public int getUnfocusedMonthDateColor() { return mFocusedMonthDateColor; } /** * Sets the color for the week numbers. * * @param color The week number color. * * @attr ref android.R.styleable#CalendarView_weekNumberColor */ public void setWeekNumberColor(int color) { if (mWeekNumberColor != color) { mWeekNumberColor = color; if (mShowWeekNumber) { invalidateAllWeekViews(); } } } /** * Gets the color for the week numbers. * * @return The week number color. * * @attr ref android.R.styleable#CalendarView_weekNumberColor */ public int getWeekNumberColor() { return mWeekNumberColor; } /** * Sets the color for the separator line between weeks. * * @param color The week separator color. * * @attr ref android.R.styleable#CalendarView_weekSeparatorLineColor */ public void setWeekSeparatorLineColor(int color) { if (mWeekSeparatorLineColor != color) { mWeekSeparatorLineColor = color; invalidateAllWeekViews(); } } /** * Gets the color for the separator line between weeks. * * @return The week separator color. * * @attr ref android.R.styleable#CalendarView_weekSeparatorLineColor */ public int getWeekSeparatorLineColor() { return mWeekSeparatorLineColor; } /** * Sets the drawable for the vertical bar shown at the beginning and at * the end of the selected date. * * @param resourceId The vertical bar drawable resource id. * * @attr ref android.R.styleable#CalendarView_selectedDateVerticalBar */ public void setSelectedDateVerticalBar(int resourceId) { Drawable drawable = getResources().getDrawable(resourceId); setSelectedDateVerticalBar(drawable); } /** * Sets the drawable for the vertical bar shown at the beginning and at * the end of the selected date. * * @param drawable The vertical bar drawable. * * @attr ref android.R.styleable#CalendarView_selectedDateVerticalBar */ public void setSelectedDateVerticalBar(Drawable drawable) { if (mSelectedDateVerticalBar != drawable) { mSelectedDateVerticalBar = drawable; final int childCount = mListView.getChildCount(); for (int i = 0; i < childCount; i ) { WeekView weekView = (WeekView) mListView.getChildAt(i); if (weekView.mHasSelectedDay) { weekView.invalidate(); } } } } /** * Gets the drawable for the vertical bar shown at the beginning and at * the end of the selected date. * * @return The vertical bar drawable. */ public Drawable getSelectedDateVerticalBar() { return mSelectedDateVerticalBar; } /** * Sets the text appearance for the week day abbreviation of the calendar header. * * @param resourceId The text appearance resource id. * * @attr ref android.R.styleable#CalendarView_weekDayTextAppearance */ public void setWeekDayTextAppearance(int resourceId) { if (mWeekDayTextAppearanceResId != resourceId) { mWeekDayTextAppearanceResId = resourceId; setUpHeader(); } } /** * Gets the text appearance for the week day abbreviation of the calendar header. * * @return The text appearance resource id. * * @attr ref android.R.styleable#CalendarView_weekDayTextAppearance */ public int getWeekDayTextAppearance() { return mWeekDayTextAppearanceResId; } /** * Sets the text appearance for the calendar dates. * * @param resourceId The text appearance resource id. * * @attr ref android.R.styleable#CalendarView_dateTextAppearance */ public void setDateTextAppearance(int resourceId) { if (mDateTextAppearanceResId != resourceId) { mDateTextAppearanceResId = resourceId; updateDateTextSize(); invalidateAllWeekViews(); } } /** * Gets the text appearance for the calendar dates. * * @return The text appearance resource id. * * @attr ref android.R.styleable#CalendarView_dateTextAppearance */ public int getDateTextAppearance() { return mDateTextAppearanceResId; } @Override public void setEnabled(boolean enabled) { mListView.setEnabled(enabled); } @Override public boolean isEnabled() { return mListView.isEnabled(); } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setCurrentLocale(newConfig.locale); } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setClassName(CalendarView.class.getName()); } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName(CalendarView.class.getName()); } /** * Gets the minimal date supported by this {@link CalendarView} in milliseconds * since January 1, 1970 00:00:00 in {@link TimeZone#getDefault()} time * zone. * <p> * Note: The default minimal date is 01/01/1900. * <p> * * @return The minimal supported date. * * @attr ref android.R.styleable#CalendarView_minDate */ public long getMinDate() { return mMinDate.getTimeInMillis(); } /** * Sets the minimal date supported by this {@link CalendarView} in milliseconds * since January 1, 1970 00:00:00 in {@link TimeZone#getDefault()} time * zone. * * @param minDate The minimal supported date. * * @attr ref android.R.styleable#CalendarView_minDate */ public void setMinDate(long minDate) { mTempDate.setTimeInMillis(minDate); if (isSameDate(mTempDate, mMinDate)) { return; } mMinDate.setTimeInMillis(minDate); // make sure the current date is not earlier than // the new min date since the latter is used for // calculating the indices in the adapter thus // avoiding out of bounds error Calendar date = mAdapter.mSelectedDate; if (date.before(mMinDate)) { mAdapter.setSelectedDay(mMinDate); } // reinitialize the adapter since its range depends on min date mAdapter.init(); if (date.before(mMinDate)) { setDate(mTempDate.getTimeInMillis()); } else { // we go to the current date to force the ListView to query its // adapter for the shown views since we have changed the adapter // range and the base from which the later calculates item indices // note that calling setDate will not work since the date is the same goTo(date, false, true, false); } } /** * Gets the maximal date supported by this {@link CalendarView} in milliseconds * since January 1, 1970 00:00:00 in {@link TimeZone#getDefault()} time * zone. * <p> * Note: The default maximal date is 01/01/2100. * <p> * * @return The maximal supported date. * * @attr ref android.R.styleable#CalendarView_maxDate */ public long getMaxDate() { return mMaxDate.getTimeInMillis(); } /** * Sets the maximal date supported by this {@link CalendarView} in milliseconds * since January 1, 1970 00:00:00 in {@link TimeZone#getDefault()} time * zone. * * @param maxDate The maximal supported date. * * @attr ref android.R.styleable#CalendarView_maxDate */ public void setMaxDate(long maxDate) { mTempDate.setTimeInMillis(maxDate); if (isSameDate(mTempDate, mMaxDate)) { return; } mMaxDate.setTimeInMillis(maxDate); // reinitialize the adapter since its range depends on max date mAdapter.init(); Calendar date = mAdapter.mSelectedDate; if (date.after(mMaxDate)) { setDate(mMaxDate.getTimeInMillis()); } else { // we go to the current date to force the ListView to query its // adapter for the shown views since we have changed the adapter // range and the base from which the later calculates item indices // note that calling setDate will not work since the date is the same goTo(date, false, true, false); } } /** * Sets whether to show the week number. * * @param showWeekNumber True to show the week number. * * @attr ref android.R.styleable#CalendarView_showWeekNumber */ public void setShowWeekNumber(boolean showWeekNumber) { if (mShowWeekNumber == showWeekNumber) { return; } mShowWeekNumber = showWeekNumber; mAdapter.notifyDataSetChanged(); setUpHeader(); } /** * Gets whether to show the week number. * * @return True if showing the week number. * * @attr ref android.R.styleable#CalendarView_showWeekNumber */ public boolean getShowWeekNumber() { return mShowWeekNumber; } /** * Gets the first day of week. * * @return The first day of the week conforming to the {@link CalendarView} * APIs. * @see Calendar#MONDAY * @see Calendar#TUESDAY * @see Calendar#WEDNESDAY * @see Calendar#THURSDAY * @see Calendar#FRIDAY * @see Calendar#SATURDAY * @see Calendar#SUNDAY * * @attr ref android.R.styleable#CalendarView_firstDayOfWeek */ public int getFirstDayOfWeek() { return mFirstDayOfWeek; } /** * Sets the first day of week. * * @param firstDayOfWeek The first day of the week conforming to the * {@link CalendarView} APIs. * @see Calendar#MONDAY * @see Calendar#TUESDAY * @see Calendar#WEDNESDAY * @see Calendar#THURSDAY * @see Calendar#FRIDAY * @see Calendar#SATURDAY * @see Calendar#SUNDAY * * @attr ref android.R.styleable#CalendarView_firstDayOfWeek */ public void setFirstDayOfWeek(int firstDayOfWeek) { if (mFirstDayOfWeek == firstDayOfWeek) { return; } mFirstDayOfWeek = firstDayOfWeek; mAdapter.init(); mAdapter.notifyDataSetChanged(); setUpHeader(); } /** * Sets the listener to be notified upon selected date change. * * @param listener The listener to be notified. */ public void setOnDateChangeListener(OnDateChangeListener listener) { mOnDateChangeListener = listener; } /** * Gets the selected date in milliseconds since January 1, 1970 00:00:00 in * {@link TimeZone#getDefault()} time zone. * * @return The selected date. */ public long getDate() { return mAdapter.mSelectedDate.getTimeInMillis(); } /** * Sets the selected date in milliseconds since January 1, 1970 00:00:00 in * {@link TimeZone#getDefault()} time zone. * * @param date The selected date. * * @throws IllegalArgumentException of the provided date is before the * minimal or after the maximal date. * * @see #setDate(long, boolean, boolean) * @see #setMinDate(long) * @see #setMaxDate(long) */ public void setDate(long date) { setDate(date, false, false); } /** * Sets the selected date in milliseconds since January 1, 1970 00:00:00 in * {@link TimeZone#getDefault()} time zone. * * @param date The date. * @param animate Whether to animate the scroll to the current date. * @param center Whether to center the current date even if it is already visible. * * @throws IllegalArgumentException of the provided date is before the * minimal or after the maximal date. * * @see #setMinDate(long) * @see #setMaxDate(long) */ public void setDate(long date, boolean animate, boolean center) { mTempDate.setTimeInMillis(date); if (isSameDate(mTempDate, mAdapter.mSelectedDate)) { return; } goTo(mTempDate, animate, true, center); } private void updateDateTextSize() { TypedArray dateTextAppearance = getContext().obtainStyledAttributes( mDateTextAppearanceResId, R.styleable.TextAppearanceCompatStyleable); mDateTextSize = dateTextAppearance.getDimensionPixelSize( R.styleable.TextAppearanceCompatStyleable_android_textSize, DEFAULT_DATE_TEXT_SIZE); dateTextAppearance.recycle(); } /** * Invalidates all week views. */ private void invalidateAllWeekViews() { final int childCount = mListView.getChildCount(); for (int i = 0; i < childCount; i ) { View view = mListView.getChildAt(i); view.invalidate(); } } /** * Sets the current locale. * * @param locale The current locale. */ private void setCurrentLocale(Locale locale) { if (locale.equals(mCurrentLocale)) { return; } mCurrentLocale = locale; mTempDate = getCalendarForLocale(mTempDate, locale); mFirstDayOfMonth = getCalendarForLocale(mFirstDayOfMonth, locale); mMinDate = getCalendarForLocale(mMinDate, locale); mMaxDate = getCalendarForLocale(mMaxDate, locale); } /** * Gets a calendar for locale bootstrapped with the value of a given calendar. * * @param oldCalendar The old calendar. * @param locale The locale. */ private Calendar getCalendarForLocale(Calendar oldCalendar, Locale locale) { if (oldCalendar == null) { return Calendar.getInstance(locale); } else { final long currentTimeMillis = oldCalendar.getTimeInMillis(); Calendar newCalendar = Calendar.getInstance(locale); newCalendar.setTimeInMillis(currentTimeMillis); return newCalendar; } } /** * @return True if the <code>firstDate</code> is the same as the <code> * secondDate</code>. */ private boolean isSameDate(Calendar firstDate, Calendar secondDate) { return (firstDate.get(Calendar.DAY_OF_YEAR) == secondDate.get(Calendar.DAY_OF_YEAR) && firstDate.get(Calendar.YEAR) == secondDate.get(Calendar.YEAR)); } /** * Creates a new adapter if necessary and sets up its parameters. */ private void setUpAdapter() { if (mAdapter == null) { mAdapter = new WeeksAdapter(getContext()); mAdapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { if (mOnDateChangeListener != null) { Calendar selectedDay = mAdapter.getSelectedDay(); mOnDateChangeListener.onSelectedDayChange(CalendarView.this, selectedDay.get(Calendar.YEAR), selectedDay.get(Calendar.MONTH), selectedDay.get(Calendar.DAY_OF_MONTH)); } } }); mListView.setAdapter(mAdapter); } // refresh the view with the new parameters mAdapter.notifyDataSetChanged(); } /** * Sets up the strings to be used by the header. */ private void setUpHeader() { mDayLabels = new String[mDaysPerWeek]; for (int i = mFirstDayOfWeek, count = mFirstDayOfWeek mDaysPerWeek; i < count; i ) { int calendarDay = (i > Calendar.SATURDAY) ? i - Calendar.SATURDAY : i; mDayLabels[i - mFirstDayOfWeek] = DateUtils.getDayOfWeekString(calendarDay, DateUtils.LENGTH_SHORTEST); } TextView label = (TextView) mDayNamesHeader.getChildAt(0); if (mShowWeekNumber) { label.setVisibility(View.VISIBLE); } else { label.setVisibility(View.GONE); } for (int i = 1, count = mDayNamesHeader.getChildCount(); i < count; i ) { label = (TextView) mDayNamesHeader.getChildAt(i); if (mWeekDayTextAppearanceResId > -1) { label.setTextAppearance(getContext(), mWeekDayTextAppearanceResId); } if (i < mDaysPerWeek 1) { label.setText(mDayLabels[i - 1]); label.setVisibility(View.VISIBLE); } else { label.setVisibility(View.GONE); } } mDayNamesHeader.invalidate(); } /** * Sets all the required fields for the list view. */ private void setUpListView() { // Configure the listview mListView.setDivider(null); mListView.setItemsCanFocus(true); mListView.setVerticalScrollBarEnabled(false); mListView.setOnScrollListener(new OnScrollListener() { public void onScrollStateChanged(AbsListView view, int scrollState) { CalendarView.this.onScrollStateChanged(view, scrollState); } public void onScroll( AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { CalendarView.this.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } }); // Make the scrolling behavior nicer if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mListView.setFriction(mFriction); mListView.setVelocityScale(mVelocityScale); } } /** * This moves to the specified time in the view. If the time is not already * in range it will move the list so that the first of the month containing * the time is at the top of the view. If the new time is already in view * the list will not be scrolled unless forceScroll is true. This time may * optionally be highlighted as selected as well. * * @param date The time to move to. * @param animate Whether to scroll to the given time or just redraw at the * new location. * @param setSelected Whether to set the given time as selected. * @param forceScroll Whether to recenter even if the time is already * visible. * * @throws IllegalArgumentException of the provided date is before the * range start of after the range end. */ private void goTo(Calendar date, boolean animate, boolean setSelected, boolean forceScroll) { if (date.before(mMinDate) || date.after(mMaxDate)) { throw new IllegalArgumentException("Time not between " mMinDate.getTime() " and " mMaxDate.getTime()); } // Find the first and last entirely visible weeks int firstFullyVisiblePosition = mListView.getFirstVisiblePosition(); View firstChild = mListView.getChildAt(0); if (firstChild != null && firstChild.getTop() < 0) { firstFullyVisiblePosition ; } int lastFullyVisiblePosition = firstFullyVisiblePosition mShownWeekCount - 1; if (firstChild != null && firstChild.getTop() > mBottomBuffer) { lastFullyVisiblePosition--; } if (setSelected) { mAdapter.setSelectedDay(date); } // Get the week we're going to int position = getWeeksSinceMinDate(date); // Check if the selected day is now outside of our visible range // and if so scroll to the month that contains it if (position < firstFullyVisiblePosition || position > lastFullyVisiblePosition || forceScroll) { mFirstDayOfMonth.setTimeInMillis(date.getTimeInMillis()); mFirstDayOfMonth.set(Calendar.DAY_OF_MONTH, 1); setMonthDisplayed(mFirstDayOfMonth); // the earliest time we can scroll to is the min date if (mFirstDayOfMonth.before(mMinDate)) { position = 0; } else { position = getWeeksSinceMinDate(mFirstDayOfMonth); } mPreviousScrollState = OnScrollListener.SCROLL_STATE_FLING; if (animate) { mListView.smoothScrollToPositionFromTop(position, mListScrollTopOffset, GOTO_SCROLL_DURATION); } else { mListView.setSelectionFromTop(position, mListScrollTopOffset); // Perform any after scroll operations that are needed onScrollStateChanged(mListView, OnScrollListener.SCROLL_STATE_IDLE); } } else if (setSelected) { // Otherwise just set the selection setMonthDisplayed(date); } } /** * Parses the given <code>date</code> and in case of success sets * the result to the <code>outDate</code>. * * @return True if the date was parsed. */ private boolean parseDate(String date, Calendar outDate) { try { outDate.setTime(mDateFormat.parse(date)); return true; } catch (ParseException e) { Log.w(LOG_TAG, "Date: " date " not in format: " DATE_FORMAT); return false; } } /** * Called when a <code>view</code> transitions to a new <code>scrollState * </code>. */ private void onScrollStateChanged(AbsListView view, int scrollState) { mScrollStateChangedRunnable.doScrollStateChange(view, scrollState); } /** * Updates the title and selected month if the <code>view</code> has moved to a new * month. */ private void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { WeekView child = (WeekView) view.getChildAt(0); if (child == null) { return; } // Figure out where we are long currScroll = view.getFirstVisiblePosition() * child.getHeight() - child.getBottom(); // If we have moved since our last call update the direction if (currScroll < mPreviousScrollPosition) { mIsScrollingUp = true; } else if (currScroll > mPreviousScrollPosition) { mIsScrollingUp = false; } else { return; } // Use some hysteresis for checking which month to highlight. This // causes the month to transition when two full weeks of a month are // visible when scrolling up, and when the first day in a month reaches // the top of the screen when scrolling down. int offset = child.getBottom() < mWeekMinVisibleHeight ? 1 : 0; if (mIsScrollingUp) { child = (WeekView) view.getChildAt(SCROLL_HYST_WEEKS offset); } else if (offset != 0) { child = (WeekView) view.getChildAt(offset); } // Find out which month we're moving into int month; if (mIsScrollingUp) { month = child.getMonthOfFirstWeekDay(); } else { month = child.getMonthOfLastWeekDay(); } // And how it relates to our current highlighted month int monthDiff; if (mCurrentMonthDisplayed == 11 && month == 0) { monthDiff = 1; } else if (mCurrentMonthDisplayed == 0 && month == 11) { monthDiff = -1; } else { monthDiff = month - mCurrentMonthDisplayed; } // Only switch months if we're scrolling away from the currently // selected month if ((!mIsScrollingUp && monthDiff > 0) || (mIsScrollingUp && monthDiff < 0)) { Calendar firstDay = child.getFirstDay(); if (mIsScrollingUp) { firstDay.add(Calendar.DAY_OF_MONTH, -DAYS_PER_WEEK); } else { firstDay.add(Calendar.DAY_OF_MONTH, DAYS_PER_WEEK); } setMonthDisplayed(firstDay); } mPreviousScrollPosition = currScroll; mPreviousScrollState = mCurrentScrollState; } /** * Sets the month displayed at the top of this view based on time. Override * to add custom events when the title is changed. * * @param calendar A day in the new focus month. */ private void setMonthDisplayed(Calendar calendar) { final int newMonthDisplayed = calendar.get(Calendar.MONTH); if (mCurrentMonthDisplayed != newMonthDisplayed) { mCurrentMonthDisplayed = newMonthDisplayed; mAdapter.setFocusMonth(mCurrentMonthDisplayed); final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_SHOW_YEAR; final long millis = calendar.getTimeInMillis(); String newMonthName = DateUtils.formatDateRange(getContext(), millis, millis, flags); mMonthName.setText(newMonthName); mMonthName.invalidate(); } } /** * @return Returns the number of weeks between the current <code>date</code> * and the <code>mMinDate</code>. */ private int getWeeksSinceMinDate(Calendar date) { if (date.before(mMinDate)) { throw new IllegalArgumentException("fromDate: " mMinDate.getTime() " does not precede toDate: " date.getTime()); } long endTimeMillis = date.getTimeInMillis() date.getTimeZone().getOffset(date.getTimeInMillis()); long startTimeMillis = mMinDate.getTimeInMillis() mMinDate.getTimeZone().getOffset(mMinDate.getTimeInMillis()); long dayOffsetMillis = (mMinDate.get(Calendar.DAY_OF_WEEK) - mFirstDayOfWeek) * MILLIS_IN_DAY; return (int) ((endTimeMillis - startTimeMillis dayOffsetMillis) / MILLIS_IN_WEEK); } /** * Command responsible for acting upon scroll state changes. */ private class ScrollStateRunnable implements Runnable { private AbsListView mView; private int mNewState; /** * Sets up the runnable with a short delay in case the scroll state * immediately changes again. * * @param view The list view that changed state * @param scrollState The new state it changed to */ public void doScrollStateChange(AbsListView view, int scrollState) { mView = view; mNewState = scrollState; removeCallbacks(this); postDelayed(this, SCROLL_CHANGE_DELAY); } public void run() { mCurrentScrollState = mNewState; // Fix the position after a scroll or a fling ends if (mNewState == OnScrollListener.SCROLL_STATE_IDLE && mPreviousScrollState != OnScrollListener.SCROLL_STATE_IDLE) { View child = mView.getChildAt(0); if (child == null) { // The view is no longer visible, just return return; } int dist = child.getBottom() - mListScrollTopOffset; if (dist > mListScrollTopOffset) { if (mIsScrollingUp) { mView.smoothScrollBy(dist - child.getHeight(), ADJUSTMENT_SCROLL_DURATION); } else { mView.smoothScrollBy(dist, ADJUSTMENT_SCROLL_DURATION); } } } mPreviousScrollState = mNewState; } } /** * <p> * This is a specialized adapter for creating a list of weeks with * selectable days. It can be configured to display the week number, start * the week on a given day, show a reduced number of days, or display an * arbitrary number of weeks at a time. * </p> */ private class WeeksAdapter extends BaseAdapter implements OnTouchListener { private int mSelectedWeek; private GestureDetector mGestureDetector; private int mFocusedMonth; private final Calendar mSelectedDate = Calendar.getInstance(); private int mTotalWeekCount; public WeeksAdapter(Context context) { mGestureDetector = new GestureDetector(getContext(), new CalendarGestureListener()); init(); } /** * Set up the gesture detector and selected time */ private void init() { mSelectedWeek = getWeeksSinceMinDate(mSelectedDate); mTotalWeekCount = getWeeksSinceMinDate(mMaxDate); if (mMinDate.get(Calendar.DAY_OF_WEEK) != mFirstDayOfWeek || mMaxDate.get(Calendar.DAY_OF_WEEK) != mFirstDayOfWeek) { mTotalWeekCount ; } } /** * Updates the selected day and related parameters. * * @param selectedDay The time to highlight */ public void setSelectedDay(Calendar selectedDay) { if (selectedDay.get(Calendar.DAY_OF_YEAR) == mSelectedDate.get(Calendar.DAY_OF_YEAR) && selectedDay.get(Calendar.YEAR) == mSelectedDate.get(Calendar.YEAR)) { return; } mSelectedDate.setTimeInMillis(selectedDay.getTimeInMillis()); mSelectedWeek = getWeeksSinceMinDate(mSelectedDate); mFocusedMonth = mSelectedDate.get(Calendar.MONTH); notifyDataSetChanged(); } /** * @return The selected day of month. */ public Calendar getSelectedDay() { return mSelectedDate; } @Override public int getCount() { return mTotalWeekCount; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { WeekView weekView = null; if (convertView != null) { weekView = (WeekView) convertView; } else { weekView = new WeekView(getContext()); android.widget.AbsListView.LayoutParams params = new android.widget.AbsListView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); weekView.setLayoutParams(params); weekView.setClickable(true); weekView.setOnTouchListener(this); } int selectedWeekDay = (mSelectedWeek == position) ? mSelectedDate.get( Calendar.DAY_OF_WEEK) : -1; weekView.init(position, selectedWeekDay, mFocusedMonth); return weekView; } /** * Changes which month is in focus and updates the view. * * @param month The month to show as in focus [0-11] */ public void setFocusMonth(int month) { if (mFocusedMonth == month) { return; } mFocusedMonth = month; notifyDataSetChanged(); } @Override public boolean onTouch(View v, MotionEvent event) { if (mListView.isEnabled() && mGestureDetector.onTouchEvent(event)) { WeekView weekView = (WeekView) v; // if we cannot find a day for the given location we are done if (!weekView.getDayFromLocation(event.getX(), mTempDate)) { return true; } // it is possible that the touched day is outside the valid range // we draw whole weeks but range end can fall not on the week end if (mTempDate.before(mMinDate) || mTempDate.after(mMaxDate)) { return true; } onDateTapped(mTempDate); return true; } return false; } /** * Maintains the same hour/min/sec but moves the day to the tapped day. * * @param day The day that was tapped */ private void onDateTapped(Calendar day) { setSelectedDay(day); setMonthDisplayed(day); } /** * This is here so we can identify single tap events and set the * selected day correctly */ class CalendarGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } } } /** * <p> * This is a dynamic view for drawing a single week. It can be configured to * display the week number, start the week on a given day, or show a reduced * number of days. It is intended for use as a single view within a * ListView. See {@link WeeksAdapter} for usage. * </p> */ private class WeekView extends View { private final Rect mTempRect = new Rect(); private final Paint mDrawPaint = new Paint(); private final Paint mMonthNumDrawPaint = new Paint(); // Cache the number strings so we don't have to recompute them each time private String[] mDayNumbers; // Quick lookup for checking which days are in the focus month private boolean[] mFocusDay; // Whether this view has a focused day. private boolean mHasFocusedDay; // Whether this view has only focused days. private boolean mHasUnfocusedDay; // The first day displayed by this item private Calendar mFirstDay; // The month of the first day in this week private int mMonthOfFirstWeekDay = -1; // The month of the last day in this week private int mLastWeekDayMonth = -1; // The position of this week, equivalent to weeks since the week of Jan // 1st, 1900 private int mWeek = -1; // Quick reference to the width of this view, matches parent private int mWidth; // The height this view should draw at in pixels, set by height param private int mHeight; // If this view contains the selected day private boolean mHasSelectedDay = false; // Which day is selected [0-6] or -1 if no day is selected private int mSelectedDay = -1; // The number of days a spot for week number if it is displayed private int mNumCells; // The left edge of the selected day private int mSelectedLeft = -1; // The right edge of the selected day private int mSelectedRight = -1; public WeekView(Context context) { super(context); // Sets up any standard paints that will be used initilaizePaints(); } /** * Initializes this week view. * * @param weekNumber The number of the week this view represents. The * week number is a zero based index of the weeks since * {@link CalendarView#getMinDate()}. * @param selectedWeekDay The selected day of the week from 0 to 6, -1 if no * selected day. * @param focusedMonth The month that is currently in focus i.e. * highlighted. */ public void init(int weekNumber, int selectedWeekDay, int focusedMonth) { mSelectedDay = selectedWeekDay; mHasSelectedDay = mSelectedDay != -1; mNumCells = mShowWeekNumber ? mDaysPerWeek 1 : mDaysPerWeek; mWeek = weekNumber; mTempDate.setTimeInMillis(mMinDate.getTimeInMillis()); mTempDate.add(Calendar.WEEK_OF_YEAR, mWeek); mTempDate.setFirstDayOfWeek(mFirstDayOfWeek); // Allocate space for caching the day numbers and focus values mDayNumbers = new String[mNumCells]; mFocusDay = new boolean[mNumCells]; // If we're showing the week number calculate it based on Monday int i = 0; if (mShowWeekNumber) { mDayNumbers[0] = String.format(Locale.getDefault(), "%d", mTempDate.get(Calendar.WEEK_OF_YEAR)); i ; } // Now adjust our starting day based on the start day of the week int diff = mFirstDayOfWeek - mTempDate.get(Calendar.DAY_OF_WEEK); mTempDate.add(Calendar.DAY_OF_MONTH, diff); mFirstDay = (Calendar) mTempDate.clone(); mMonthOfFirstWeekDay = mTempDate.get(Calendar.MONTH); mHasUnfocusedDay = true; for (; i < mNumCells; i ) { final boolean isFocusedDay = (mTempDate.get(Calendar.MONTH) == focusedMonth); mFocusDay[i] = isFocusedDay; mHasFocusedDay |= isFocusedDay; mHasUnfocusedDay &= !isFocusedDay; // do not draw dates outside the valid range to avoid user confusion if (mTempDate.before(mMinDate) || mTempDate.after(mMaxDate)) { mDayNumbers[i] = ""; } else { mDayNumbers[i] = String.format(Locale.getDefault(), "%d", mTempDate.get(Calendar.DAY_OF_MONTH)); } mTempDate.add(Calendar.DAY_OF_MONTH, 1); } // We do one extra add at the end of the loop, if that pushed us to // new month undo it if (mTempDate.get(Calendar.DAY_OF_MONTH) == 1) { mTempDate.add(Calendar.DAY_OF_MONTH, -1); } mLastWeekDayMonth = mTempDate.get(Calendar.MONTH); updateSelectionPositions(); } /** * Initialize the paint instances. */ private void initilaizePaints() { mDrawPaint.setFakeBoldText(false); mDrawPaint.setAntiAlias(true); mDrawPaint.setStyle(Style.FILL); mMonthNumDrawPaint.setFakeBoldText(true); mMonthNumDrawPaint.setAntiAlias(true); mMonthNumDrawPaint.setStyle(Style.FILL); mMonthNumDrawPaint.setTextAlign(Align.CENTER); mMonthNumDrawPaint.setTextSize(mDateTextSize); } /** * Returns the month of the first day in this week. * * @return The month the first day of this view is in. */ public int getMonthOfFirstWeekDay() { return mMonthOfFirstWeekDay; } /** * Returns the month of the last day in this week * * @return The month the last day of this view is in */ public int getMonthOfLastWeekDay() { return mLastWeekDayMonth; } /** * Returns the first day in this view. * * @return The first day in the view. */ public Calendar getFirstDay() { return mFirstDay; } /** * Calculates the day that the given x position is in, accounting for * week number. * * @param x The x position of the touch event. * @return True if a day was found for the given location. */ public boolean getDayFromLocation(float x, Calendar outCalendar) { final boolean isLayoutRtl = isLayoutRtl(); int start; int end; if (isLayoutRtl) { start = 0; end = mShowWeekNumber ? mWidth - mWidth / mNumCells : mWidth; } else { start = mShowWeekNumber ? mWidth / mNumCells : 0; end = mWidth; } if (x < start || x > end) { outCalendar.clear(); return false; } // Selection is (x - start) / (pixels/day) which is (x - start) * day / pixels int dayPosition = (int) ((x - start) * mDaysPerWeek / (end - start)); if (isLayoutRtl) { dayPosition = mDaysPerWeek - 1 - dayPosition; } outCalendar.setTimeInMillis(mFirstDay.getTimeInMillis()); outCalendar.add(Calendar.DAY_OF_MONTH, dayPosition); return true; } @Override protected void onDraw(Canvas canvas) { drawBackground(canvas); drawWeekNumbersAndDates(canvas); drawWeekSeparators(canvas); drawSelectedDateVerticalBars(canvas); } /** * This draws the selection highlight if a day is selected in this week. * * @param canvas The canvas to draw on */ private void drawBackground(Canvas canvas) { if (!mHasSelectedDay) { return; } mDrawPaint.setColor(mSelectedWeekBackgroundColor); mTempRect.top = mWeekSeperatorLineWidth; mTempRect.bottom = mHeight; final boolean isLayoutRtl = isLayoutRtl(); if (isLayoutRtl) { mTempRect.left = 0; mTempRect.right = mSelectedLeft - 2; } else { mTempRect.left = mShowWeekNumber ? mWidth / mNumCells : 0; mTempRect.right = mSelectedLeft - 2; } canvas.drawRect(mTempRect, mDrawPaint); if (isLayoutRtl) { mTempRect.left = mSelectedRight 3; mTempRect.right = mShowWeekNumber ? mWidth - mWidth / mNumCells : mWidth; } else { mTempRect.left = mSelectedRight 3; mTempRect.right = mWidth; } canvas.drawRect(mTempRect, mDrawPaint); } /** * Draws the week and month day numbers for this week. * * @param canvas The canvas to draw on */ private void drawWeekNumbersAndDates(Canvas canvas) { final float textHeight = mDrawPaint.getTextSize(); final int y = (int) ((mHeight textHeight) / 2) - mWeekSeperatorLineWidth; final int nDays = mNumCells; final int divisor = 2 * nDays; mDrawPaint.setTextAlign(Align.CENTER); mDrawPaint.setTextSize(mDateTextSize); int i = 0; if (isLayoutRtl()) { for (; i < nDays - 1; i ) { mMonthNumDrawPaint.setColor(mFocusDay[i] ? mFocusedMonthDateColor : mUnfocusedMonthDateColor); int x = (2 * i 1) * mWidth / divisor; canvas.drawText(mDayNumbers[nDays - 1 - i], x, y, mMonthNumDrawPaint); } if (mShowWeekNumber) { mDrawPaint.setColor(mWeekNumberColor); int x = mWidth - mWidth / divisor; canvas.drawText(mDayNumbers[0], x, y, mDrawPaint); } } else { if (mShowWeekNumber) { mDrawPaint.setColor(mWeekNumberColor); int x = mWidth / divisor; canvas.drawText(mDayNumbers[0], x, y, mDrawPaint); i ; } for (; i < nDays; i ) { mMonthNumDrawPaint.setColor(mFocusDay[i] ? mFocusedMonthDateColor : mUnfocusedMonthDateColor); int x = (2 * i 1) * mWidth / divisor; canvas.drawText(mDayNumbers[i], x, y, mMonthNumDrawPaint); } } } /** * Draws a horizontal line for separating the weeks. * * @param canvas The canvas to draw on. */ private void drawWeekSeparators(Canvas canvas) { // If it is the topmost fully visible child do not draw separator line int firstFullyVisiblePosition = mListView.getFirstVisiblePosition(); if (mListView.getChildAt(0).getTop() < 0) { firstFullyVisiblePosition ; } if (firstFullyVisiblePosition == mWeek) { return; } mDrawPaint.setColor(mWeekSeparatorLineColor); mDrawPaint.setStrokeWidth(mWeekSeperatorLineWidth); float startX; float stopX; if (isLayoutRtl()) { startX = 0; stopX = mShowWeekNumber ? mWidth - mWidth / mNumCells : mWidth; } else { startX = mShowWeekNumber ? mWidth / mNumCells : 0; stopX = mWidth; } canvas.drawLine(startX, 0, stopX, 0, mDrawPaint); } /** * Draws the selected date bars if this week has a selected day. * * @param canvas The canvas to draw on */ private void drawSelectedDateVerticalBars(Canvas canvas) { if (!mHasSelectedDay) { return; } mSelectedDateVerticalBar.setBounds(mSelectedLeft - mSelectedDateVerticalBarWidth / 2, mWeekSeperatorLineWidth, mSelectedLeft mSelectedDateVerticalBarWidth / 2, mHeight); mSelectedDateVerticalBar.draw(canvas); mSelectedDateVerticalBar.setBounds(mSelectedRight - mSelectedDateVerticalBarWidth / 2, mWeekSeperatorLineWidth, mSelectedRight mSelectedDateVerticalBarWidth / 2, mHeight); mSelectedDateVerticalBar.draw(canvas); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { mWidth = w; updateSelectionPositions(); } /** * This calculates the positions for the selected day lines. */ private void updateSelectionPositions() { if (mHasSelectedDay) { final boolean isLayoutRtl = isLayoutRtl(); int selectedPosition = mSelectedDay - mFirstDayOfWeek; if (selectedPosition < 0 ) { selectedPosition = 7 ; } if (mShowWeekNumber && !isLayoutRtl) { selectedPosition ; } if (isLayoutRtl) { mSelectedLeft = (mDaysPerWeek - 1 - selectedPosition) * mWidth / mNumCells; } else { mSelectedLeft = selectedPosition * mWidth / mNumCells; } mSelectedRight = mSelectedLeft mWidth / mNumCells; } } @Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec) { mHeight = (mListView.getHeight() - mListView.getPaddingTop() - mListView .getPaddingBottom()) / mShownWeekCount; setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), mHeight); } } private boolean isLayoutRtl() { // No API17 in maven central.. //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // return getLayoutDirection() == LAYOUT_DIRECTION_RTL; //} return false ; } } |
标签: 日历
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论