Android使用GridView实现日历功能(详细代码)

时间:2023-03-09 01:10:45
Android使用GridView实现日历功能(详细代码)

代码有点多,发个图先:

Android使用GridView实现日历功能(详细代码)

如果懒得往下看的,可以直接下载源码吧(0分的),最近一直有人要,由于时间太久了,懒得找出来整理,今天又看到有人要,正好没事就整理了一下

http://download.****.net/detail/onlyonecoder/6574379

布局文件:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <LinearLayout
  7. android:id="@+id/lay_title"
  8. style="@style/TitleStyle"
  9. android:layout_width="fill_parent" >
  10. <TextView
  11. android:id="@+id/btn_back"
  12. style="@style/TitleLeftButtonStyle" />
  13. <TextView
  14. android:id="@+id/tv_top"
  15. style="@style/TitleMiddleTextStyle"
  16. android:text="请选择日期" />
  17. <TextView
  18. android:id="@+id/btn_goback_to_today"
  19. style="@style/TitleRightButtonStyle"
  20. android:text="今天" />
  21. </LinearLayout>
  22. <LinearLayout
  23. android:layout_width="fill_parent"
  24. android:layout_height="53.0dip"
  25. android:background="#ff394147"
  26. android:gravity="center_vertical" >
  27. <LinearLayout
  28. android:id="@+id/btn_prev_month"
  29. android:layout_width="0.0dip"
  30. android:layout_height="fill_parent"
  31. android:layout_weight="0.2"
  32. android:gravity="center"
  33. android:orientation="vertical" >
  34. <TextView
  35. android:id="@+id/left_img"
  36. android:layout_width="wrap_content"
  37. android:layout_height="wrap_content"
  38. android:background="@drawable/triangle06_states"
  39. android:duplicateParentState="true"
  40. android:text=""
  41. android:textSize="16.0dip" />
  42. </LinearLayout>
  43. <LinearLayout
  44. android:layout_width="0.0dip"
  45. android:layout_height="fill_parent"
  46. android:layout_weight="0.6"
  47. android:gravity="center"
  48. android:orientation="vertical" >
  49. <TextView
  50. android:id="@+id/tv_month"
  51. android:layout_width="wrap_content"
  52. android:layout_height="wrap_content"
  53. android:gravity="center"
  54. android:text="xxxx年14月"
  55. android:textColor="#ffffffff"
  56. android:textSize="21.0dip" />
  57. </LinearLayout>
  58. <LinearLayout
  59. android:id="@+id/btn_next_month"
  60. android:layout_width="0.0dip"
  61. android:layout_height="fill_parent"
  62. android:layout_weight="0.2"
  63. android:gravity="center"
  64. android:orientation="vertical" >
  65. <TextView
  66. android:id="@+id/right_img"
  67. android:layout_width="wrap_content"
  68. android:layout_height="wrap_content"
  69. android:background="@drawable/triangle05_states"
  70. android:duplicateParentState="true"
  71. android:text=""
  72. android:textSize="16.0dip" />
  73. </LinearLayout>
  74. </LinearLayout>
  75. <LinearLayout
  76. android:layout_width="fill_parent"
  77. android:layout_height="22.0dip"
  78. android:background="#ff8091a8" >
  79. <TextView
  80. android:layout_width="0.0dip"
  81. android:layout_height="wrap_content"
  82. android:layout_gravity="center"
  83. android:layout_weight="1.0"
  84. android:gravity="center"
  85. android:text="周日"
  86. android:textColor="#ffffffff"
  87. android:textSize="14.0dip" />
  88. <TextView
  89. android:layout_width="0.0dip"
  90. android:layout_height="wrap_content"
  91. android:layout_gravity="center"
  92. android:layout_weight="1.0"
  93. android:gravity="center"
  94. android:text="周一"
  95. android:textColor="#ffffffff"
  96. android:textSize="14.0dip" />
  97. <TextView
  98. android:layout_width="0.0dip"
  99. android:layout_height="wrap_content"
  100. android:layout_gravity="center"
  101. android:layout_weight="1.0"
  102. android:gravity="center"
  103. android:text="周二"
  104. android:textColor="#ffffffff"
  105. android:textSize="14.0dip" />
  106. <TextView
  107. android:layout_width="0.0dip"
  108. android:layout_height="wrap_content"
  109. android:layout_gravity="center"
  110. android:layout_weight="1.0"
  111. android:gravity="center"
  112. android:text="周三"
  113. android:textColor="#ffffffff"
  114. android:textSize="14.0dip" />
  115. <TextView
  116. android:layout_width="0.0dip"
  117. android:layout_height="wrap_content"
  118. android:layout_gravity="center"
  119. android:layout_weight="1.0"
  120. android:gravity="center"
  121. android:text="周四"
  122. android:textColor="#ffffffff"
  123. android:textSize="14.0dip" />
  124. <TextView
  125. android:layout_width="0.0dip"
  126. android:layout_height="wrap_content"
  127. android:layout_gravity="center"
  128. android:layout_weight="1.0"
  129. android:gravity="center"
  130. android:text="周五"
  131. android:textColor="#ffffffff"
  132. android:textSize="14.0dip" />
  133. <TextView
  134. android:layout_width="0.0dip"
  135. android:layout_height="wrap_content"
  136. android:layout_gravity="center"
  137. android:layout_weight="1.0"
  138. android:gravity="center"
  139. android:text="周六"
  140. android:textColor="#ffffffff"
  141. android:textSize="14.0dip" />
  142. </LinearLayout>
  143. <GridView
  144. android:id="@+id/gridview"
  145. android:layout_width="fill_parent"
  146. android:layout_height="wrap_content"
  147. android:background="#00000000"
  148. android:clickable="true"
  149. android:clipChildren="true"
  150. android:columnWidth="55.0dip"
  151. android:horizontalSpacing="1.0dip"
  152. android:listSelector="@null"
  153. android:numColumns="7"
  154. android:paddingBottom="1.0dip"
  155. android:stretchMode="columnWidth"
  156. android:verticalSpacing="1.0dip" />
  157. </LinearLayout>

Item:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:background="#FFFFFF"
  5. android:layout_width="fill_parent"
  6. android:layout_height="fill_parent">
  7. <TextView
  8. android:gravity="center"
  9. android:layout_width="46dp"
  10. android:layout_height="55dp"
  11. android:id="@+id/tvtext"
  12. />
  13. </LinearLayout><strong><span style="font-size:32px;color:#ff0000;">
  14. </span></strong>

 

Adapter:

  1. /**
  2. * 日历gridview中的每一个item显示的textview
  3. * @author lmw
  4. *
  5. */
  6. public class CalendarAdapter extends BaseAdapter {
  7. private boolean isLeapyear = false;  //是否为闰年
  8. private int daysOfMonth = 0;      //某月的天数
  9. private int dayOfWeek = 0;        //具体某一天是星期几
  10. private int lastDaysOfMonth = 0;  //上一个月的总天数
  11. private Context context;
  12. private String[] dayNumber = new String[42];  //一个gridview中的日期存入此数组中
  13. //  private static String week[] = {"周日","周一","周二","周三","周四","周五","周六"};
  14. private SpecialCalendar sc = null;
  15. private LunarCalendar lc = null;
  16. private Resources res = null;
  17. private Drawable drawable = null;
  18. private String currentYear = "";
  19. private String currentMonth = "";
  20. private String currentDay = "";
  21. private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
  22. private int currentFlag = -1;     //用于标记当天
  23. private int[] schDateTagFlag = null;  //存储当月所有的日程日期
  24. private String showYear = "";   //用于在头部显示的年份
  25. private String showMonth = "";  //用于在头部显示的月份
  26. private String animalsYear = "";
  27. private String leapMonth = "";   //闰哪一个月
  28. private String cyclical = "";   //天干地支
  29. //系统当前时间
  30. private String sysDate = "";
  31. private String sys_year = "";
  32. private String sys_month = "";
  33. private String sys_day = "";
  34. public CalendarAdapter(){
  35. Date date = new Date();
  36. sysDate = sdf.format(date);  //当期日期
  37. sys_year = sysDate.split("-")[0];
  38. sys_month = sysDate.split("-")[1];
  39. sys_day = sysDate.split("-")[2];
  40. }
  41. public CalendarAdapter(Context context,Resources rs,int jumpMonth,int jumpYear,int year_c,int month_c,int day_c){
  42. this();
  43. this.context= context;
  44. sc = new SpecialCalendar();
  45. lc = new LunarCalendar();
  46. this.res = rs;
  47. int stepYear = year_c+jumpYear;
  48. int stepMonth = month_c+jumpMonth ;
  49. if(stepMonth > 0){
  50. //往下一个月滑动
  51. if(stepMonth%12 == 0){
  52. stepYear = year_c + stepMonth/12 -1;
  53. stepMonth = 12;
  54. }else{
  55. stepYear = year_c + stepMonth/12;
  56. stepMonth = stepMonth%12;
  57. }
  58. }else{
  59. //往上一个月滑动
  60. stepYear = year_c - 1 + stepMonth/12;
  61. stepMonth = stepMonth%12 + 12;
  62. if(stepMonth%12 == 0){
  63. }
  64. }
  65. currentYear = String.valueOf(stepYear);;  //得到当前的年份
  66. currentMonth = String.valueOf(stepMonth);  //得到本月 (jumpMonth为滑动的次数,每滑动一次就增加一月或减一月)
  67. currentDay = String.valueOf(day_c);  //得到当前日期是哪天
  68. getCalendar(Integer.parseInt(currentYear),Integer.parseInt(currentMonth));
  69. }
  70. public CalendarAdapter(Context context,Resources rs,int year, int month, int day){
  71. this();
  72. this.context= context;
  73. sc = new SpecialCalendar();
  74. lc = new LunarCalendar();
  75. this.res = rs;
  76. currentYear = String.valueOf(year);;  //得到跳转到的年份
  77. currentMonth = String.valueOf(month);  //得到跳转到的月份
  78. currentDay = String.valueOf(day);  //得到跳转到的天
  79. getCalendar(Integer.parseInt(currentYear),Integer.parseInt(currentMonth));
  80. }
  81. @Override
  82. public int getCount() {
  83. // TODO Auto-generated method stub
  84. return dayNumber.length;
  85. }
  86. @Override
  87. public Object getItem(int position) {
  88. // TODO Auto-generated method stub
  89. return position;
  90. }
  91. @Override
  92. public long getItemId(int position) {
  93. // TODO Auto-generated method stub
  94. return position;
  95. }
  96. @Override
  97. public View getView(int position, View convertView, ViewGroup parent) {
  98. if(convertView == null){
  99. convertView = LayoutInflater.from(context).inflate(R.layout.calendar_item, null);
  100. }
  101. TextView textView = (TextView) convertView.findViewById(R.id.tvtext);
  102. String d = dayNumber[position].split("\\.")[0];
  103. String dv = dayNumber[position].split("\\.")[1];
  104. SpannableString sp = new SpannableString(d+"\n"+dv);
  105. sp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, d.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  106. sp.setSpan(new RelativeSizeSpan(1.2f) , 0, d.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  107. if(dv != null ||dv != ""){
  108. sp.setSpan(new RelativeSizeSpan(0.75f), d.length()+1, dayNumber[position].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  109. }
  110. //      sp.setSpan(new ForegroundColorSpan(Color.MAGENTA), 14, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
  111. textView.setText(sp);
  112. textView.setTextColor(Color.GRAY);
  113. //      if(position<7){
  114. //          //设置周
  115. //          textView.setTextColor(Color.WHITE);
  116. //          textView.setBackgroundColor(color.search_txt_color);
  117. //          textView.setTextSize(14);
  118. //      }
  119. if (position < daysOfMonth + dayOfWeek && position >= dayOfWeek) {
  120. // 当前月信息显示
  121. textView.setTextColor(Color.BLACK);// 当月字体设黑
  122. drawable = res.getDrawable(R.drawable.current_day_bgc);
  123. }
  124. if(schDateTagFlag != null && schDateTagFlag.length >0){
  125. for(int i = 0; i < schDateTagFlag.length; i++){
  126. if(schDateTagFlag[i] == position){
  127. //设置日程标记背景
  128. textView.setBackgroundResource(R.drawable.mark);
  129. }
  130. }
  131. }
  132. if(currentFlag == position){
  133. //设置当天的背景
  134. drawable = res.getDrawable(R.drawable.current_day_bgc);
  135. textView.setBackgroundDrawable(drawable);
  136. textView.setTextColor(Color.WHITE);
  137. }
  138. return convertView;
  139. }
  140. //得到某年的某月的天数且这月的第一天是星期几
  141. public void getCalendar(int year, int month){
  142. isLeapyear = sc.isLeapYear(year);              //是否为闰年
  143. daysOfMonth = sc.getDaysOfMonth(isLeapyear, month);  //某月的总天数
  144. dayOfWeek = sc.getWeekdayOfMonth(year, month);      //某月第一天为星期几
  145. lastDaysOfMonth = sc.getDaysOfMonth(isLeapyear, month-1);  //上一个月的总天数
  146. Log.d("DAY", isLeapyear+" ======  "+daysOfMonth+"  ============  "+dayOfWeek+"  =========   "+lastDaysOfMonth);
  147. getweek(year,month);
  148. }
  149. //将一个月中的每一天的值添加入数组dayNuber中
  150. private void getweek(int year, int month) {
  151. int j = 1;
  152. int flag = 0;
  153. String lunarDay = "";
  154. //得到当前月的所有日程日期(这些日期需要标记)
  155. for (int i = 0; i < dayNumber.length; i++) {
  156. // 周一
  157. //          if(i<7){
  158. //              dayNumber[i]=week[i]+"."+" ";
  159. //          }
  160. if(i < dayOfWeek){  //前一个月
  161. int temp = lastDaysOfMonth - dayOfWeek+1;
  162. lunarDay = lc.getLunarDate(year, month-1, temp+i,false);
  163. dayNumber[i] = (temp + i)+"."+lunarDay;
  164. }else if(i < daysOfMonth + dayOfWeek){   //本月
  165. String day = String.valueOf(i-dayOfWeek+1);   //得到的日期
  166. lunarDay = lc.getLunarDate(year, month, i-dayOfWeek+1,false);
  167. dayNumber[i] = i-dayOfWeek+1+"."+lunarDay;
  168. //对于当前月才去标记当前日期
  169. if(sys_year.equals(String.valueOf(year)) && sys_month.equals(String.valueOf(month)) && sys_day.equals(day)){
  170. //标记当前日期
  171. currentFlag = i;
  172. }
  173. setShowYear(String.valueOf(year));
  174. setShowMonth(String.valueOf(month));
  175. setAnimalsYear(lc.animalsYear(year));
  176. setLeapMonth(lc.leapMonth == 0?"":String.valueOf(lc.leapMonth));
  177. setCyclical(lc.cyclical(year));
  178. }else{   //下一个月
  179. lunarDay = lc.getLunarDate(year, month+1, j,false);
  180. dayNumber[i] = j+"."+lunarDay;
  181. j++;
  182. }
  183. }
  184. String abc = "";
  185. for(int i = 0; i < dayNumber.length; i++){
  186. abc = abc+dayNumber[i]+":";
  187. }
  188. Log.d("DAYNUMBER",abc);
  189. }
  190. public void matchScheduleDate(int year, int month, int day){
  191. }
  192. /**
  193. * 点击每一个item时返回item中的日期
  194. * @param position
  195. * @return
  196. */
  197. public String getDateByClickItem(int position){
  198. return dayNumber[position];
  199. }
  200. /**
  201. * 在点击gridView时,得到这个月中第一天的位置
  202. * @return
  203. */
  204. public int getStartPositon(){
  205. return dayOfWeek+7;
  206. }
  207. /**
  208. * 在点击gridView时,得到这个月中最后一天的位置
  209. * @return
  210. */
  211. public int getEndPosition(){
  212. return  (dayOfWeek+daysOfMonth+7)-1;
  213. }
  214. public String getShowYear() {
  215. return showYear;
  216. }
  217. public void setShowYear(String showYear) {
  218. this.showYear = showYear;
  219. }
  220. public String getShowMonth() {
  221. return showMonth;
  222. }
  223. public void setShowMonth(String showMonth) {
  224. this.showMonth = showMonth;
  225. }
  226. public String getAnimalsYear() {
  227. return animalsYear;
  228. }
  229. public void setAnimalsYear(String animalsYear) {
  230. this.animalsYear = animalsYear;
  231. }
  232. public String getLeapMonth() {
  233. return leapMonth;
  234. }
  235. public void setLeapMonth(String leapMonth) {
  236. this.leapMonth = leapMonth;
  237. }
  238. public String getCyclical() {
  239. return cyclical;
  240. }
  241. public void setCyclical(String cyclical) {
  242. this.cyclical = cyclical;
  243. }
  244. }

计算类

  1. import java.util.Calendar;
  2. public class SpecialCalendar {
  3. private int daysOfMonth = 0;      //某月的天数
  4. private int dayOfWeek = 0;        //具体某一天是星期几
  5. // 判断是否为闰年
  6. public boolean isLeapYear(int year) {
  7. if (year % 100 == 0 && year % 400 == 0) {
  8. return true;
  9. } else if (year % 100 != 0 && year % 4 == 0) {
  10. return true;
  11. }
  12. return false;
  13. }
  14. //得到某月有多少天数
  15. public int getDaysOfMonth(boolean isLeapyear, int month) {
  16. switch (month) {
  17. case 1:
  18. case 3:
  19. case 5:
  20. case 7:
  21. case 8:
  22. case 10:
  23. case 12:
  24. daysOfMonth = 31;
  25. break;
  26. case 4:
  27. case 6:
  28. case 9:
  29. case 11:
  30. daysOfMonth = 30;
  31. break;
  32. case 2:
  33. if (isLeapyear) {
  34. daysOfMonth = 29;
  35. } else {
  36. daysOfMonth = 28;
  37. }
  38. }
  39. return daysOfMonth;
  40. }
  41. //指定某年中的某月的第一天是星期几
  42. public int getWeekdayOfMonth(int year, int month){
  43. Calendar cal = Calendar.getInstance();
  44. cal.set(year, month-1, 1);
  45. dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1;
  46. return dayOfWeek;
  47. }
  48. }

节日和阴历计算类

关于日历实现代码里0x04bd8, 0x04ae0, 0x0a570的解释:

http://blog.****.net/onlyonecoder/article/details/8484118

  1. public class LunarCalendar {
  2. private int year;   //农历的年份
  3. private int month;
  4. private int day;
  5. private String lunarMonth;   //农历的月份
  6. private boolean leap;
  7. public int leapMonth = 0;   //闰的是哪个月
  8. final static String chineseNumber[] = { "一", "二", "三", "四", "五", "六", "七",
  9. "八", "九", "十", "十一", "十二" };
  10. static SimpleDateFormat chineseDateFormat = new SimpleDateFormat(
  11. "yyyy年MM月dd日");
  12. final static long[] lunarInfo = new long[] { 0x04bd8, 0x04ae0, 0x0a570,
  13. 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,
  14. 0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0,
  15. 0x0ada2, 0x095b0, 0x14977, 0x04970, 0x0a4b0, 0x0b4b5, 0x06a50,
  16. 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970, 0x06566,
  17. 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0,
  18. 0x1c8d7, 0x0c950, 0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4,
  19. 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557, 0x06ca0, 0x0b550,
  20. 0x15355, 0x04da0, 0x0a5d0, 0x14573, 0x052d0, 0x0a9a8, 0x0e950,
  21. 0x06aa0, 0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260,
  22. 0x0f263, 0x0d950, 0x05b57, 0x056a0, 0x096d0, 0x04dd5, 0x04ad0,
  23. 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b5a0, 0x195a6,
  24. 0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40,
  25. 0x0af46, 0x0ab60, 0x09570, 0x04af5, 0x04970, 0x064b0, 0x074a3,
  26. 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0, 0x0c960,
  27. 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0,
  28. 0x092d0, 0x0cab5, 0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9,
  29. 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930, 0x07954, 0x06aa0,
  30. 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65,
  31. 0x0d530, 0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0,
  32. 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45, 0x0b5a0, 0x056d0, 0x055b2,
  33. 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0 };
  34. //农历部分假日
  35. final static String[] lunarHoliday = new String[]{
  36. "0101 春节",
  37. "0115 元宵",
  38. "0505 端午",
  39. "0707 七夕情人",
  40. "0715 中元",
  41. "0815 中秋",
  42. "0909 重阳",
  43. "1208 腊八",
  44. "1224 小年",
  45. "0100 除夕"
  46. };
  47. //公历部分节假日
  48. final static String[] solarHoliday = new String[]{
  49. "0101 元旦",
  50. "0214 情人",
  51. "0308 妇女",
  52. "0312 植树",
  53. "0315 消费者权益日",
  54. "0401 愚人",
  55. "0501 劳动",
  56. "0504 青年",
  57. "0512 护士",
  58. "0601 儿童",
  59. "0701 建党",
  60. "0801 建军",
  61. "0808 父亲",
  62. "0909 XXX逝世纪念",
  63. "0910 教师",
  64. "0928 孔子诞辰",
  65. "1001 国庆",
  66. "1006 老人",
  67. "1024 联合国日",
  68. "1112 孙中山诞辰纪念",
  69. "1220 澳门回归纪念",
  70. "1225 圣诞",
  71. "1226 XXX诞辰纪念"
  72. };
  73. // ====== 传回农历 y年的总天数
  74. final private static int yearDays(int y) {
  75. int i, sum = 348;
  76. for (i = 0x8000; i > 0x8; i >>= 1) {
  77. if ((lunarInfo[y - 1900] & i) != 0)
  78. sum += 1;
  79. }
  80. return (sum + leapDays(y));
  81. }
  82. // ====== 传回农历 y年闰月的天数
  83. final private static int leapDays(int y) {
  84. if (leapMonth(y) != 0) {
  85. if ((lunarInfo[y - 1900] & 0x10000) != 0)
  86. return 30;
  87. else
  88. return 29;
  89. } else
  90. return 0;
  91. }
  92. // ====== 传回农历 y年闰哪个月 1-12 , 没闰传回 0
  93. final private static int leapMonth(int y) {
  94. return (int) (lunarInfo[y - 1900] & 0xf);
  95. }
  96. // ====== 传回农历 y年m月的总天数
  97. final private static int monthDays(int y, int m) {
  98. if ((lunarInfo[y - 1900] & (0x10000 >> m)) == 0)
  99. return 29;
  100. else
  101. return 30;
  102. }
  103. // ====== 传回农历 y年的生肖
  104. final public String animalsYear(int year) {
  105. final String[] Animals = new String[] { "鼠", "牛", "虎", "兔", "龙", "蛇",
  106. "马", "羊", "猴", "鸡", "狗", "猪" };
  107. return Animals[(year - 4) % 12];
  108. }
  109. // ====== 传入 月日的offset 传回干支, 0=甲子
  110. final private static String cyclicalm(int num) {
  111. final String[] Gan = new String[] { "甲", "乙", "丙", "丁", "戊", "己", "庚",
  112. "辛", "壬", "癸" };
  113. final String[] Zhi = new String[] { "子", "丑", "寅", "卯", "辰", "巳", "午",
  114. "未", "申", "酉", "戌", "亥" };
  115. return (Gan[num % 10] + Zhi[num % 12]);
  116. }
  117. // ====== 传入 offset 传回干支, 0=甲子
  118. final public String cyclical(int year) {
  119. int num = year - 1900 + 36;
  120. return (cyclicalm(num));
  121. }
  122. public static String getChinaDayString(int day) {
  123. String chineseTen[] = { "初", "十", "廿", "卅" };
  124. int n = day % 10 == 0 ? 9 : day % 10 - 1;
  125. if (day > 30)
  126. return "";
  127. if (day == 10)
  128. return "初十";
  129. else
  130. return chineseTen[day / 10] + chineseNumber[n];
  131. }
  132. /** */
  133. /**
  134. * 传出y年m月d日对应的农历. yearCyl3:农历年与1864的相差数 ? monCyl4:从1900年1月31日以来,闰月数
  135. * dayCyl5:与1900年1月31日相差的天数,再加40 ?
  136. *
  137. * isday: 这个参数为false---日期为节假日时,阴历日期就返回节假日 ,true---不管日期是否为节假日依然返回这天对应的阴历日期
  138. * @param cal
  139. * @return
  140. */
  141. public String getLunarDate(int year_log, int month_log, int day_log, boolean isday) {
  142. // @SuppressWarnings("unused")
  143. int yearCyl, monCyl, dayCyl;
  144. //int leapMonth = 0;
  145. String nowadays;
  146. Date baseDate = null;
  147. Date nowaday = null;
  148. try {
  149. baseDate = chineseDateFormat.parse("1900年1月31日");
  150. } catch (ParseException e) {
  151. e.printStackTrace(); // To change body of catch statement use
  152. // Options | File Templates.
  153. }
  154. nowadays = year_log + "年" + month_log + "月" + day_log + "日";
  155. try {
  156. nowaday = chineseDateFormat.parse(nowadays);
  157. } catch (ParseException e) {
  158. e.printStackTrace(); // To change body of catch statement use
  159. // Options | File Templates.
  160. }
  161. // 求出和1900年1月31日相差的天数
  162. int offset = (int) ((nowaday.getTime() - baseDate.getTime()) / 86400000L);
  163. dayCyl = offset + 40;
  164. monCyl = 14;
  165. // 用offset减去每农历年的天数
  166. // 计算当天是农历第几天
  167. // i最终结果是农历的年份
  168. // offset是当年的第几天
  169. int iYear, daysOfYear = 0;
  170. for (iYear = 1900; iYear < 10000 && offset > 0; iYear++) {
  171. daysOfYear = yearDays(iYear);
  172. offset -= daysOfYear;
  173. monCyl += 12;
  174. }
  175. if (offset < 0) {
  176. offset += daysOfYear;
  177. iYear--;
  178. monCyl -= 12;
  179. }
  180. // 农历年份
  181. year = iYear;
  182. setYear(year);  //设置公历对应的农历年份
  183. yearCyl = iYear - 1864;
  184. leapMonth = leapMonth(iYear); // 闰哪个月,1-12
  185. leap = false;
  186. // 用当年的天数offset,逐个减去每月(农历)的天数,求出当天是本月的第几天
  187. int iMonth, daysOfMonth = 0;
  188. for (iMonth = 1; iMonth < 13 && offset > 0; iMonth++) {
  189. // 闰月
  190. if (leapMonth > 0 && iMonth == (leapMonth + 1) && !leap) {
  191. --iMonth;
  192. leap = true;
  193. daysOfMonth = leapDays(year);
  194. } else
  195. daysOfMonth = monthDays(year, iMonth);
  196. offset -= daysOfMonth;
  197. // 解除闰月
  198. if (leap && iMonth == (leapMonth + 1))
  199. leap = false;
  200. if (!leap)
  201. monCyl++;
  202. }
  203. // offset为0时,并且刚才计算的月份是闰月,要校正
  204. if (offset == 0 && leapMonth > 0 && iMonth == leapMonth + 1) {
  205. if (leap) {
  206. leap = false;
  207. } else {
  208. leap = true;
  209. --iMonth;
  210. --monCyl;
  211. }
  212. }
  213. // offset小于0时,也要校正
  214. if (offset < 0) {
  215. offset += daysOfMonth;
  216. --iMonth;
  217. --monCyl;
  218. }
  219. month = iMonth;
  220. setLunarMonth(chineseNumber[month - 1] + "月");  //设置对应的阴历月份
  221. day = offset + 1;
  222. if(!isday){
  223. //如果日期为节假日则阴历日期则返回节假日
  224. //setLeapMonth(leapMonth);
  225. for(int i = 0; i < solarHoliday.length; i++){
  226. //返回公历节假日名称
  227. String sd = solarHoliday[i].split(" ")[0];  //节假日的日期
  228. String sdv = solarHoliday[i].split(" ")[1]; //节假日的名称
  229. String smonth_v = month_log+"";
  230. String sday_v = day_log+"";
  231. String smd = "";
  232. if(month_log < 10){
  233. smonth_v = "0"+month_log;
  234. }
  235. if(day_log < 10){
  236. sday_v = "0"+day_log;
  237. }
  238. smd = smonth_v+sday_v;
  239. if(sd.trim().equals(smd.trim())){
  240. return sdv;
  241. }
  242. }
  243. for(int i = 0; i < lunarHoliday.length; i++){
  244. //返回农历节假日名称
  245. String ld =lunarHoliday[i].split(" ")[0];   //节假日的日期
  246. String ldv = lunarHoliday[i].split(" ")[1];  //节假日的名称
  247. String lmonth_v = month+"";
  248. String lday_v = day+"";
  249. String lmd = "";
  250. if(month < 10){
  251. lmonth_v = "0"+month;
  252. }
  253. if(day < 10){
  254. lday_v = "0"+day;
  255. }
  256. lmd = lmonth_v+lday_v;
  257. if(ld.trim().equals(lmd.trim())){
  258. return ldv;
  259. }
  260. }
  261. }
  262. if (day == 1)
  263. return chineseNumber[month - 1] + "月";
  264. else
  265. return getChinaDayString(day);
  266. }
  267. public String toString() {
  268. if (chineseNumber[month - 1] == "一" && getChinaDayString(day) == "初一")
  269. return "农历" + year + "年";
  270. else if (getChinaDayString(day) == "初一")
  271. return chineseNumber[month - 1] + "月";
  272. else
  273. return getChinaDayString(day);
  274. // return year + "年" + (leap ? "闰" : "") + chineseNumber[month - 1] +
  275. // "月" + getChinaDayString(day);
  276. }
  277. /*public static void main(String[] args) {
  278. System.out.println(new LunarCalendar().getLunarDate(2012, 1, 23));
  279. }*/
  280. public int getLeapMonth() {
  281. return leapMonth;
  282. }
  283. public void setLeapMonth(int leapMonth) {
  284. this.leapMonth = leapMonth;
  285. }
  286. /**
  287. * 得到当前日期对应的阴历月份
  288. * @return
  289. */
  290. public String getLunarMonth() {
  291. return lunarMonth;
  292. }
  293. public void setLunarMonth(String lunarMonth) {
  294. this.lunarMonth = lunarMonth;
  295. }
  296. /**
  297. * 得到当前年对应的农历年份
  298. * @return
  299. */
  300. public int getYear() {
  301. return year;
  302. }
  303. public void setYear(int year) {
  304. this.year = year;
  305. }
  306. }

Activity

    1. /**
    2. * 日历显示activity
    3. *
    4. *
    5. */
    6. public class CalendarActivity extends Activity implements OnGestureListener {
    7. private GestureDetector gestureDetector = null;
    8. private CalendarAdapter calV = null;
    9. private GridView gridView = null;
    10. private TextView topText = null;
    11. private static int jumpMonth = 0;      //每次滑动,增加或减去一个月,默认为0(即显示当前月)
    12. private static int jumpYear = 0;       //滑动跨越一年,则增加或者减去一年,默认为0(即当前年)
    13. private int year_c = 0;
    14. private int month_c = 0;
    15. private int day_c = 0;
    16. private String currentDate = "";
    17. private Bundle bd=null;//发送参数
    18. private Bundle bun=null;//接收参数
    19. private String ruzhuTime;
    20. private String lidianTime;
    21. private String state="";
    22. public CalendarActivity() {
    23. Date date = new Date();
    24. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
    25. currentDate = sdf.format(date);  //当期日期
    26. year_c = Integer.parseInt(currentDate.split("-")[0]);
    27. month_c = Integer.parseInt(currentDate.split("-")[1]);
    28. day_c = Integer.parseInt(currentDate.split("-")[2]);
    29. }
    30. @Override
    31. public void onCreate(Bundle savedInstanceState) {
    32. super.onCreate(savedInstanceState);
    33. ActivityList.activityList.add(this);
    34. setContentView(R.layout.calendar);
    35. bd=new Bundle();//out
    36. bun=getIntent().getExtras();//in
    37. if(bun!=null&&bun.getString("state").equals("ruzhu"))
    38. {
    39. state=bun.getString("state");
    40. System.out.println("%%%%%%"+state);
    41. }else if(bun!=null&&bun.getString("state").equals("lidian")){
    42. state=bun.getString("state");
    43. System.out.println("|||||||||||"+state);
    44. }
    45. gestureDetector = new GestureDetector(this);
    46. //      bd=new Bundle();
    47. calV = new CalendarAdapter(this,getResources(),jumpMonth,jumpYear,year_c,month_c,day_c);
    48. addGridView();
    49. gridView.setAdapter(calV);
    50. topText = (TextView) findViewById(R.id.tv_month);
    51. addTextToTopTextView(topText);
    52. }
    53. @Override
    54. public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
    55. float velocityY) {
    56. int gvFlag = 0;         //每次添加gridview到viewflipper中时给的标记
    57. if (e1.getX() - e2.getX() > 120) {
    58. //像左滑动
    59. addGridView();   //添加一个gridView
    60. jumpMonth++;     //下一个月
    61. calV = new CalendarAdapter(this,getResources(),jumpMonth,jumpYear,year_c,month_c,day_c);
    62. gridView.setAdapter(calV);
    63. addTextToTopTextView(topText);
    64. gvFlag++;
    65. return true;
    66. } else if (e1.getX() - e2.getX() < -120) {
    67. //向右滑动
    68. addGridView();   //添加一个gridView
    69. jumpMonth--;     //上一个月
    70. calV = new CalendarAdapter(this,getResources(),jumpMonth,jumpYear,year_c,month_c,day_c);
    71. gridView.setAdapter(calV);
    72. gvFlag++;
    73. addTextToTopTextView(topText);
    74. return true;
    75. }
    76. return false;
    77. }
    78. /**
    79. * 创建菜单
    80. */
    81. @Override
    82. public boolean onCreateOptionsMenu(Menu menu) {
    83. menu.add(0, menu.FIRST, menu.FIRST, "今天");
    84. return super.onCreateOptionsMenu(menu);
    85. }
    86. /**
    87. * 选择菜单
    88. */
    89. @Override
    90. public boolean onMenuItemSelected(int featureId, MenuItem item) {
    91. switch (item.getItemId()){
    92. case Menu.FIRST:
    93. //跳转到今天
    94. int xMonth = jumpMonth;
    95. int xYear = jumpYear;
    96. int gvFlag =0;
    97. jumpMonth = 0;
    98. jumpYear = 0;
    99. addGridView();   //添加一个gridView
    100. year_c = Integer.parseInt(currentDate.split("-")[0]);
    101. month_c = Integer.parseInt(currentDate.split("-")[1]);
    102. day_c = Integer.parseInt(currentDate.split("-")[2]);
    103. calV = new CalendarAdapter(this,getResources(),jumpMonth,jumpYear,year_c,month_c,day_c);
    104. gridView.setAdapter(calV);
    105. addTextToTopTextView(topText);
    106. gvFlag++;
    107. break;
    108. }
    109. return super.onMenuItemSelected(featureId, item);
    110. }
    111. @Override
    112. public boolean onTouchEvent(MotionEvent event) {
    113. return this.gestureDetector.onTouchEvent(event);
    114. }
    115. @Override
    116. public boolean onDown(MotionEvent e) {
    117. // TODO Auto-generated method stub
    118. return false;
    119. }
    120. @Override
    121. public void onLongPress(MotionEvent e) {
    122. // TODO Auto-generated method stub
    123. }
    124. @Override
    125. public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
    126. float distanceY) {
    127. // TODO Auto-generated method stub
    128. return false;
    129. }
    130. @Override
    131. public void onShowPress(MotionEvent e) {
    132. // TODO Auto-generated method stub
    133. }
    134. @Override
    135. public boolean onSingleTapUp(MotionEvent e) {
    136. // TODO Auto-generated method stub
    137. return false;
    138. }
    139. //添加头部的年份 闰哪月等信息
    140. public void addTextToTopTextView(TextView view){
    141. StringBuffer textDate = new StringBuffer();
    142. textDate.append(calV.getShowYear()).append("年").append(
    143. calV.getShowMonth()).append("月").append("\t");
    144. view.setText(textDate);
    145. view.setTextColor(Color.WHITE);
    146. view.setTypeface(Typeface.DEFAULT_BOLD);
    147. }
    148. //添加gridview
    149. private void addGridView() {
    150. gridView =(GridView)findViewById(R.id.gridview);
    151. gridView.setOnTouchListener(new OnTouchListener() {
    152. //将gridview中的触摸事件回传给gestureDetector
    153. @Override
    154. public boolean onTouch(View v, MotionEvent event) {
    155. // TODO Auto-generated method stub
    156. return CalendarActivity.this.gestureDetector.onTouchEvent(event);
    157. }
    158. });
    159. gridView.setOnItemClickListener(new OnItemClickListener() {
    160. //gridView中的每一个item的点击事件
    161. @Override
    162. public void onItemClick(AdapterView<?> arg0, View arg1, int position,
    163. long arg3) {
    164. //点击任何一个item,得到这个item的日期(排除点击的是周日到周六(点击不响应))
    165. int startPosition = calV.getStartPositon();
    166. int endPosition = calV.getEndPosition();
    167. if(startPosition <= position+7  && position <= endPosition-7){
    168. String scheduleDay = calV.getDateByClickItem(position).split("\\.")[0];  //这一天的阳历
    169. //String scheduleLunarDay = calV.getDateByClickItem(position).split("\\.")[1];  //这一天的阴历
    170. String scheduleYear = calV.getShowYear();
    171. String scheduleMonth = calV.getShowMonth();
    172. //                    Toast.makeText(CalendarActivity.this, scheduleYear+"-"+scheduleMonth+"-"+scheduleDay, 2000).show();
    173. ruzhuTime=scheduleMonth+"月"+scheduleDay+"日";
    174. lidianTime=scheduleMonth+"月"+scheduleDay+"日";
    175. Intent intent=new Intent();
    176. if(state.equals("ruzhu"))
    177. {
    178. bd.putString("ruzhu", ruzhuTime);
    179. System.out.println("ruzhuuuuuu"+bd.getString("ruzhu"));
    180. }else if(state.equals("lidian")){
    181. bd.putString("lidian", lidianTime);
    182. }
    183. intent.setClass(CalendarActivity.this, HotelActivity.class);
    184. intent.putExtras(bd);
    185. startActivity(intent);
    186. finish();
    187. }
    188. }
    189. });
    190. }
    191. }