zoukankan      html  css  js  c++  java
  • 自定义日历

    效果如图

    一、布局 main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    <RelativeLayout 
            android:id="@+id/main_head"
           android:orientation="horizontal" 
           android:layout_width="fill_parent"
        android:layout_height="38dp"
        android:background="@drawable/header_bg"
        android:layout_alignParentTop="true"
            >
            <TextView
            android:id="@+id/toptext"
            android:layout_width="80dp"
            android:layout_height="38dp"
            android:layout_centerInParent="true"
            android:gravity="center"
                />
            <Button 
            android:id="@+id/previous"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_marginRight="20dp"
            android:layout_toLeftOf="@id/toptext"    
            android:layout_centerVertical="true"
            android:background="@drawable/previous_month"/>
            
        <Button 
            android:id="@+id/next"
            android:layout_toRightOf="@id/toptext"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_marginLeft="20dp"
            android:layout_centerVertical="true"
            android:background="@drawable/next_month"
            />
        </RelativeLayout>
      <LinearLayout 
            android:id="@+id/main"
            android:layout_marginTop="18dp"
            android:orientation="vertical" 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    
    </LinearLayout>

    二、MainActivity

    package com.ct.mycalendar;
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    
    import android.app.Activity;
    import android.graphics.Color;
    import android.graphics.Typeface;
    import android.graphics.drawable.ColorDrawable;
    import android.os.Bundle;
    import android.view.Display;
    import android.view.Gravity;
    import android.view.View;
    import android.view.Window;
    import android.view.WindowManager;
    import android.widget.AbsListView.LayoutParams;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.Button;
    import android.widget.GridView;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.ct.mycalendar.tool.CalendarView;
    
    public class Calendar01Activity extends Activity {
        /** Called when the activity is first created. */
        private CalendarView calV = null;
        private GridView gridView = null;
        private TextView topText = null;
        private static int jumpMonth = 0;      //每次点击按钮,增加或减去一个月,默认为0(即显示当前月)
        private static int jumpYear = 0;       //点击超过一年,则增加或者减去一年,默认为0(即当前年)
        private int year_c = 0;
        private int month_c = 0;
        private int day_c = 0;
        private String currentDate = "";
        
        // 上一月和下一月的按钮
            Button previous;
            Button next;
            LinearLayout main;
            
            SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM");
            SimpleDateFormat format2 = new SimpleDateFormat("MMM yyyy", Locale.US);
            
            public Calendar01Activity(){
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
                currentDate  = sdf.format(date);
                year_c = Integer.parseInt(currentDate.split("-")[0]);
                month_c = Integer.parseInt(currentDate.split("-")[1]);
                day_c = Integer.parseInt(currentDate.split("-")[2]);
            }
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.main);
            
            calV = new CalendarView(this, getResources(),jumpMonth,jumpYear,year_c,month_c,day_c);
            addGridView();
            gridView.setAdapter(calV);
            previous = (Button) findViewById(R.id.previous);
            next = (Button) findViewById(R.id.next);
            
            main = (LinearLayout) findViewById(R.id.main);
            main.addView(gridView);
            
            topText = (TextView) findViewById(R.id.toptext);
            addTextToTopTextView(topText);
            
            previous.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v) 
                {
                    getPreviousMonth();
                }
            });
            
            next.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v) 
                {
                    getNextMonth();
                }
            });
            
            
        }
        
        private void addGridView(){
            WindowManager windowManager = getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            int width = display.getWidth();
            int height = display.getHeight();
            
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
            
            gridView = new GridView(this);
            gridView.setNumColumns(7);
            gridView.setColumnWidth(46);
            
            if(width == 480 && height == 800){
                gridView.setColumnWidth(69);
            }
            gridView.setGravity(Gravity.CENTER_VERTICAL);
            gridView.setSelector(new ColorDrawable(Color.GRAY)); // 去除gridView边框
            gridView.setVerticalSpacing(1);
            gridView.setHorizontalSpacing(1);
            gridView.setBackgroundResource(R.color.light_gray_bg);
            gridView.setPadding(1, 1, 1, 1);
            
            gridView.setOnItemClickListener(new OnItemClickListener() {
                //gridView中的每一个item的点击事件
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                        long arg3) {
                    
                    String scheduleDay = calV.getDateByClickItem(position).split("\\.")[0];  //这一天的阳历
                    String titleYear = calV.getShowYear();
                    String titleMonth = calV.getShowMonth();
    //                Toast.makeText(CalendarActivity.this,
    //                        "被点击的日期 : " + titleYear + "年" + titleMonth + "月" + scheduleDay + "日",
    //                        Toast.LENGTH_LONG).show();
                    
                    int startPosition = calV.getStartPositon();
                    int endPosition = calV.getEndPosition();
                    
                    if(position >= startPosition && position <= endPosition)
                    {
                        Toast.makeText(Calendar01Activity.this, "被点击的日期 : " + titleYear + "年" + titleMonth + "月" + scheduleDay + "日", Toast.LENGTH_LONG).show();
                    }
                    else if(position < startPosition)
                    {
    //                    Toast.makeText(CalendarActivity.this, "上一个月", Toast.LENGTH_LONG).show();
                        getPreviousMonth();
                    }
                    else if(position > endPosition)
                    {
    //                    Toast.makeText(CalendarActivity.this, "下一个月", Toast.LENGTH_LONG).show();
                        getNextMonth();
                    }
                    else
                    {
                        Toast.makeText(Calendar01Activity.this, "No", Toast.LENGTH_LONG).show();
                    }
                }
            });
            gridView.setLayoutParams(params);
            
        }
        
        private void getPreviousMonth(){
            jumpMonth--;
            calV = new CalendarView(Calendar01Activity.this, getResources(),jumpMonth,jumpYear,year_c,month_c,day_c);
            gridView.setAdapter(calV);
            addTextToTopTextView(topText);
        }
        
        private void getNextMonth(){
            jumpMonth++;
            calV = new CalendarView(Calendar01Activity.this, getResources(),jumpMonth,jumpYear,year_c,month_c,day_c);
            gridView.setAdapter(calV);
            addTextToTopTextView(topText);
        }
        
        private void addTextToTopTextView(TextView view){
            StringBuffer textDate = new StringBuffer();
            String datestr = calV.getShowYear() + " " + calV.getShowMonth();
            try{
                textDate.append(format2.format(format1.parse(datestr)));
            }catch (ParseException e){
                e.printStackTrace();
            }
            view.setText(textDate);
            view.setTextColor(Color.WHITE);
            view.setTypeface(Typeface.DEFAULT_BOLD);
            
        }
    }

    三、CalendarView

    package com.ct.mycalendar.tool;
    
    
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    
    import android.content.Context;
    import android.content.res.Resources;
    import android.graphics.Color;
    import android.graphics.drawable.Drawable;
    import android.text.SpannableString;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;
    
    import com.ct.mycalendar.R;
    
    /**
     * 日历gridview中的每一个item显示的textview
     * @author willm zhang
     *
     */
    public class CalendarView extends BaseAdapter {
    
    
    
    //    private ScheduleDAO dao = null;
        private boolean isLeapyear = false;  //是否为闰年
        private int daysOfMonth = 0;      //某月的天数
        private int dayOfWeek = 0;        //具体某一天是星期几
        private int lastDaysOfMonth = 0;  //上一个月的总天数
        private Context context;
        private String[] dayNumber = new String[49];  //一个gridview中的日期存入此数组中
        private SpecialCalendar sc = null;
        private Resources res = null;
        private Drawable drawable = null;
        
        private String currentYear = "";
        private String currentMonth = "";
        private String currentDay = "";
        
        private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
        private int currentFlag = -1;     //用于标记当天
        private int[] schDateTagFlag = null;  //存储当月所有的日程日期
        
        private String showYear = "";   //用于在头部显示的年份
        private String showMonth = "";  //用于在头部显示的月份
        private String animalsYear = ""; 
        private String leapMonth = "";   //闰哪一个月
        private String cyclical = "";   //天干地支
        //系统当前时间
        private String sysDate = "";  
        private String sys_year = "";
        private String sys_month = "";
        private String sys_day = "";
        
        //日程时间(需要标记的日程日期)
        private String sch_year = "";
        private String sch_month = "";
        private String sch_day = "";
        
        SpecialCalendar spe = new SpecialCalendar();
        
        public CalendarView(){
            Date date = new Date();
            sysDate = sdf.format(date);  //当期日期
            sys_year = sysDate.split("-")[0];
            sys_month = sysDate.split("-")[1];
            sys_day = sysDate.split("-")[2];
        }
    
        public CalendarView(Context context,Resources rs,int jumpMonth,int jumpYear,int year_c,int month_c,int day_c){
            this();
            this.context= context;
            sc = new SpecialCalendar();
            this.res = rs;
            
            int stepYear = year_c+jumpYear;
            int stepMonth = month_c+jumpMonth ;
            if(stepMonth > 0){
                //往下一个月跳转
                if(stepMonth%12 == 0){
                    stepYear = year_c + stepMonth/12 -1;
                    stepMonth = 12;
                }else{
                    stepYear = year_c + stepMonth/12;
                    stepMonth = stepMonth%12;
                }
            }else{
                //往上一个月跳转
                stepYear = year_c - 1 + stepMonth/12;
                stepMonth = stepMonth%12 + 12;
                if(stepMonth%12 == 0){
                    
                }
            }
            
            currentYear = String.valueOf(stepYear);;  //得到当前的年份
            currentMonth = String.valueOf(stepMonth);  //得到本月 (jumpMonth为跳动的次数,每滑动一次就增加一月或减一月)
            currentDay = String.valueOf(day_c);  //得到当前日期是哪天
            
            getCalendar(Integer.parseInt(currentYear),Integer.parseInt(currentMonth));
            
        }
        
        public CalendarView(Context context,Resources rs,int year, int month, int day){
            this();
            this.context= context;
            sc = new SpecialCalendar();
            this.res = rs;
            currentYear = String.valueOf(year);;  //得到跳转到的年份
            currentMonth = String.valueOf(month);  //得到跳转到的月份
            currentDay = String.valueOf(day);  //得到跳转到的天
            getCalendar(Integer.parseInt(currentYear),Integer.parseInt(currentMonth));
        }
        
        @Override
        public int getCount() {
            if(Integer.parseInt(currentMonth) == 2)
            {
                if(getStartPositon() == 0)
                {
                    if(! spe.isLeapYear(Integer.parseInt(currentYear)))
                    {
                        return 28;
                    }
                }
                return 35;
            }
            return getStartPositon() <= 4 ? 35 : 42;
        }
    
        @Override
        public Object getItem(int position) {
            return position;
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
    
            if(convertView == null){
                convertView = LayoutInflater.from(context).inflate(R.layout.calendar, null);
             }
            TextView textView = (TextView) convertView.findViewById(R.id.tvtext);
            String d = dayNumber[position].split("\\.")[0];
            SpannableString sp = new SpannableString(d);
            textView.setText(sp);
            textView.setTextColor(R.color.typeface_color_black);
            if (position < daysOfMonth + dayOfWeek && position >= dayOfWeek) {
                // 当前月信息显示
                textView.setTextColor(Color.BLACK);// 当月字体设黑
                drawable = res.getDrawable(R.color.calendar_bg);
                // textView.setBackgroundColor(Color.WHITE);
            }
            if(schDateTagFlag != null && schDateTagFlag.length >0){
                for(int i = 0; i < schDateTagFlag.length; i++){
                    if(schDateTagFlag[i] == position){
                        System.out.println("=============schDateTagFlag" + "[" + i+ "]=="+ position );
                        //设置日程标记背景
                        textView.setBackgroundResource(R.drawable.marker);
                    }
                }
            }
            if(currentFlag == position){ 
                //设置当天的背景
    //            drawable = res.getDrawable(R.color.bule_bg);
    //            textView.setBackgroundDrawable(drawable);
                textView.setBackgroundResource(R.drawable.selected);
                textView.setTextColor(Color.WHITE);
            }
            if(position < dayOfWeek || position >= daysOfMonth + dayOfWeek){
                //设置上一月和下一月的背景
    //            drawable = res.getDrawable(Color.GRAY);
    //            textView.setBackgroundDrawable(drawable);
                textView.setBackgroundResource(R.drawable.no_this_month);
                textView.setTextColor(Color.GRAY);
            }
            return convertView;
        }
        
        //得到某年的某月的天数且这月的第一天是星期几
        public void getCalendar(int year, int month){
            isLeapyear = sc.isLeapYear(year);              //是否为闰年
            daysOfMonth = sc.getDaysOfMonth(isLeapyear, month);  //某月的总天数
            dayOfWeek = sc.getWeekdayOfMonth(year, month);      //某月第一天为星期几
            lastDaysOfMonth = sc.getDaysOfMonth(isLeapyear, month-1);  //上一个月的总天数
            Log.d("DAY", isLeapyear+" ======  "+daysOfMonth+"  ============  "+dayOfWeek+"  =========   "+lastDaysOfMonth);
            getweek(year,month);
        }
        private ArrayList<ScheduleDateTag> getTagDate(int year, int month){
            ArrayList<ScheduleDateTag> dateTagList = new ArrayList<ScheduleDateTag>(){
                private static final long serialVersionUID = -5976649074350323408L;};
            int i = 0;
            while(i < 10){
                int tagID = i;
                int year1 = 2012;
                int month1 = 11;
                int day = 2*(i);
                int scheduleID = i;
                ScheduleDateTag dateTag = new ScheduleDateTag(tagID,year1,month1,day,scheduleID);
                dateTagList.add(dateTag);
                i++;
                }
            if(dateTagList != null && dateTagList.size() > 0){
                return dateTagList;
            }
            return null;
        }
        
        //将一个月中的每一天的值添加入数组dayNuber中
        private void getweek(int year, int month) {
            int j = 1;
            int flag = 0;
            
            //得到当前月的所有日程日期(这些日期需要标记)
    //        dao = new ScheduleDAO(context);
            ArrayList<ScheduleDateTag> dateTagList = this.getTagDate(year,month);
            if(dateTagList != null && dateTagList.size() > 0){
                schDateTagFlag = new int[dateTagList.size()];
            }
            
            for (int i = 0; i < dayNumber.length; i++) {
                // 周一
                if(i < dayOfWeek){  //前一个月
                    int temp = lastDaysOfMonth - dayOfWeek+1;
                    dayNumber[i] = (temp + i)+".";
                }else if(i < daysOfMonth + dayOfWeek){   //本月
                    String day = String.valueOf(i-dayOfWeek+1);   //得到的日期
                    dayNumber[i] = i-dayOfWeek+1+".";
                    //对于当前月才去标记当前日期
                    if(sys_year.equals(String.valueOf(year)) && sys_month.equals(String.valueOf(month)) && sys_day.equals(day)){
                        //笔记当前日期
                        currentFlag = i;
                    }
                    //标记日程日期
                    if(dateTagList != null && dateTagList.size() > 0){
                        for(int m = 0; m < dateTagList.size(); m++){
                            ScheduleDateTag dateTag = dateTagList.get(m);
                            int matchYear = dateTag.getYear();
                            int matchMonth = dateTag.getMonth();
                            int matchDay = dateTag.getDay();
                            if(matchYear == year && matchMonth == month && matchDay == Integer.parseInt(day)){
                                schDateTagFlag[flag] = i;
                                flag++;
                            }
                        }
                        
                    }
                    setShowYear(String.valueOf(year));
                    setShowMonth(String.valueOf(month));
                }else{   //下一个月
                    dayNumber[i] = j+"";
                    j++;
                }
            }
            
            String abc = "";
            for(int i = 0; i < dayNumber.length; i++){
                 abc = abc+dayNumber[i]+":";
            }
            Log.d("DAYNUMBER",abc);
    
    
        }
    //    /**
    //     * 得到所有的日程信息
    //     */
    //    public void getScheduleAll(){
    ////        schList = dao.getAllSchedule();
    //        if(schList != null){
    //            for (ScheduleVO vo : schList) {
    //                String content = vo.getScheduleContent();
    //                int startLine = content.indexOf("\n");
    //                if(startLine > 0){
    //                    content = content.substring(0, startLine)+"...";
    //                }else if(content.length() > 30){
    //                    content = content.substring(0, 30)+"...";
    //                }
    //                scheduleID = vo.getScheduleID();
    //                createInfotext(scheduleInfo, scheduleID);
    //            }
    //        }else{
    //            scheduleInfo = "没有日程";
    //            createInfotext(scheduleInfo,-1);
    //        }
    //    }
        
        
        public void matchScheduleDate(int year, int month, int day){
            
        }
        
        /**
         * 点击每一个item时返回item中的日期
         * @param position
         * @return
         */
        public String getDateByClickItem(int position){
            return dayNumber[position];
        }
        
        /**
         * 在点击gridView时,得到这个月中第一天的位置
         * @return
         */
        public int getStartPositon(){
            return dayOfWeek;
        }
        
        /**
         * 在点击gridView时,得到这个月中最后一天的位置
         * @return
         */
        public int getEndPosition(){
            return  (dayOfWeek+daysOfMonth)-1;
        }
        
        public String getShowYear() {
            return showYear;
        }
    
        public void setShowYear(String showYear) {
            this.showYear = showYear;
        }
    
        public String getShowMonth() {
            return showMonth;
        }
    
        public void setShowMonth(String showMonth) {
            this.showMonth = showMonth;
        }
        
        public String getAnimalsYear() {
            return animalsYear;
        }
    
        public void setAnimalsYear(String animalsYear) {
            this.animalsYear = animalsYear;
        }
        
        public String getLeapMonth() {
            return leapMonth;
        }
    
        public void setLeapMonth(String leapMonth) {
            this.leapMonth = leapMonth;
        }
        
        public String getCyclical() {
            return cyclical;
        }
    
        public void setCyclical(String cyclical) {
            this.cyclical = cyclical;
        }
    }

    四、SpecialCalendar

    package com.ct.mycalendar.tool;
    
    import java.util.Calendar;
    
    public class SpecialCalendar {
        /**
         * 日历工具类
         * @author willm zhang
         *
         */
    
        private int daysOfMonth = 0;      //某月的天数
        private int dayOfWeek = 0;        //具体某一天是星期几
    
        
        
        
        // 判断是否为闰年
        public boolean isLeapYear(int year) {
            if (year % 100 == 0 && year % 400 == 0) {
                return true;
            } else if (year % 100 != 0 && year % 4 == 0) {
                return true;
            }
            return false;
        }
    
        //得到某月有多少天数
        public int getDaysOfMonth(boolean isLeapyear, int month) {
            switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                daysOfMonth = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                daysOfMonth = 30;
                break;
            case 2:
                if (isLeapyear) {
                    daysOfMonth = 29;
                } else {
                    daysOfMonth = 28;
                }
    
            }
            return daysOfMonth;
        }
        
        //指定某年中的某月的第一天是星期几
        public int getWeekdayOfMonth(int year, int month){
            Calendar cal = Calendar.getInstance();
            cal.set(year, month-1, 1);
            dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1;
            return dayOfWeek;
        }
        
        
    }

    五、ScheduleDateTag

    package com.ct.mycalendar.tool;
    
    /**
     * 需要标记的日程日期
     * @author willm zhang
     *
     */
    public class ScheduleDateTag {
    
        private int tagID;
        private int scheduleTypeID;
        private int remindID;
        private int month;
        private int year;
        private int day;
        private int scheduleID;
        
        
        public ScheduleDateTag() {
            
        }
    
    
        public ScheduleDateTag(int tagID, int year, int month, int day, int scheduleID) {
    
            this.tagID = tagID;
            this.month = month;
            this.year = year;
            this.day = day;
            this.scheduleID = scheduleID;
        }
    
    
        public int getTagID() {
            return tagID;
        }
    
    
        public void setTagID(int tagID) {
            this.tagID = tagID;
        }
    
    
        public int getScheduleTypeID() {
            return scheduleTypeID;
        }
    
    
        public void setScheduleTypeID(int scheduleTypeID) {
            this.scheduleTypeID = scheduleTypeID;
        }
    
    
        public int getRemindID() {
            return remindID;
        }
    
    
        public void setRemindID(int remindID) {
            this.remindID = remindID;
        }
    
    
        public int getMonth() {
            return month;
        }
    
    
        public void setMonth(int month) {
            this.month = month;
        }
    
    
        public int getYear() {
            return year;
        }
    
    
        public void setYear(int year) {
            this.year = year;
        }
    
    
        public int getDay() {
            return day;
        }
    
    
        public void setDay(int day) {
            this.day = day;
        }
    
    
        public int getScheduleID() {
            return scheduleID;
        }
    
    
        public void setScheduleID(int scheduleID) {
            this.scheduleID = scheduleID;
        }
        
    }

    六、资源文件等等

    (在F:\java\Calendar01)

  • 相关阅读:
    SpringBoot进阶教程(六十二)整合Kafka
    98每日博客
    96每日博客
    95日每周总结
    829每周总结
    815每周总结
    81每周总结
    822每周总结
    97每日博客
    88每周总结
  • 原文地址:https://www.cnblogs.com/ct732003684/p/2859344.html
Copyright © 2011-2022 走看看