Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義日曆控件:農曆、節氣、日期標注與滑動切月

編輯:關於 Android 程式設計

系統沒有現成的日曆選擇器,很多 App(記帳、簽到、行事曆)都得自己刻一個。本文分享一個改寫自網路開源思路的 CalendarView,功能包含:農曆顯示、二十四節氣、傳統節日、公曆節日、日期標注、點擊回呼,以及左右滑動切換月份。

準備工作

控件用 getResourceAsStream 讀取箭頭圖示,因此圖片要放在與 java 檔同一層的 image 目錄下。若 CalendarView.java 位於 cc.util.android.view,就必須另建 cc.util.android.view.image 並把四張箭頭圖(含按下態)複製進去,否則執行時會拿到空圖。

整體結構

控件繼承 LinearLayout,內部由三塊組成:頂部的年月標題與左右箭頭、中部的星期標頭、底部的日期網格。日期網格用 ViewFlipper 疊放「上一月、當月、下一月」三個 GridView,切換時播放平移動畫,滑動手勢則交給 GestureDetector 判定。

主控件程式碼

package cc.util.android.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.*;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.view.*;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.*;
import android.widget.AbsListView.LayoutParams;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 日曆控件:支援農曆、節氣、日期標注與點擊操作
 */
public class CalendarView extends LinearLayout
        implements OnTouchListener, Animation.AnimationListener, GestureDetector.OnGestureListener {

    /** 點擊日曆的回呼介面 */
    public interface OnCalendarViewListener {
        void onCalendarItemClick(CalendarView view, Date date);
    }

    private static final int TOP_HEIGHT = 40;
    private static final int DEFAULT_ID = 0xff0000;

    // 手勢判定門檻
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    private static final int caltitleLayoutID = 66;
    private static final int calLayoutID = 55;

    private int screenWidth;

    private Animation slideLeftIn, slideLeftOut, slideRightIn, slideRightOut;
    private ViewFlipper viewFlipper;
    private GestureDetector mGesture;

    private GridView gView1, gView2, gView3;      // 上月 / 當月 / 下月
    private CalendarGridViewAdapter gAdapter, gAdapter1, gAdapter3;

    private Calendar calStartDate = Calendar.getInstance();  // 目前顯示的月份
    private Calendar calSelected  = Calendar.getInstance();  // 使用者選取的日期

    private final List<Date> markDates;                      // 需要標注的日期
    private OnCalendarViewListener mListener;

    private LinearLayout mMainLayout;
    private TextView mTitle;
    private ImageButton mLeftView, mRightView;

    private int iMonthViewCurrentMonth;
    private int iMonthViewCurrentYear;

    public CalendarView(Context context) {
        this(context, null);
    }

    public CalendarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        markDates = new ArrayList<Date>();
        init();
    }

    protected void init() {
        screenWidth = getResources().getDisplayMetrics().widthPixels;

        slideLeftIn   = new TranslateAnimation(screenWidth, 0, 0, 0);
        slideLeftOut  = new TranslateAnimation(0, -screenWidth, 0, 0);
        slideRightIn  = new TranslateAnimation(-screenWidth, 0, 0, 0);
        slideRightOut = new TranslateAnimation(0, screenWidth, 0, 0);
        slideLeftIn.setDuration(400);
        slideLeftOut.setDuration(400);
        slideRightIn.setDuration(400);
        slideRightOut.setDuration(400);
        slideLeftIn.setAnimationListener(this);
        slideLeftOut.setAnimationListener(this);
        slideRightIn.setAnimationListener(this);
        slideRightOut.setAnimationListener(this);

        mGesture = new GestureDetector(getContext(), this);

        UpdateStartDateForMonth();

        setOrientation(LinearLayout.HORIZONTAL);
        mMainLayout = new LinearLayout(getContext());
        mMainLayout.setLayoutParams(new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        mMainLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        mMainLayout.setOrientation(LinearLayout.VERTICAL);
        addView(mMainLayout);

        generateTopView();        // 標題列
        generateWeekGirdView();   // 星期列

        viewFlipper = new ViewFlipper(getContext());
        RelativeLayout.LayoutParams fliperParams = new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        fliperParams.addRule(RelativeLayout.BELOW, caltitleLayoutID);
        mMainLayout.addView(viewFlipper, fliperParams);
        generateClaendarGirdView();

        // 底部裝飾線
        LinearLayout br = new LinearLayout(getContext());
        br.setBackgroundColor(Color.argb(0xff, 0xe3, 0xee, 0xf4));
        mMainLayout.addView(br, new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, 3));
    }

    /** 頂部:左右箭頭 + 年月標題 */
    @SuppressWarnings("deprecation")
    private void generateTopView() {
        RelativeLayout top = new RelativeLayout(getContext());
        top.setBackgroundColor(Color.argb(0xff, 0x0e, 0x6b, 0xc2));
        top.setLayoutParams(new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, ViewUtil.dip2px(getContext(), TOP_HEIGHT)));
        mMainLayout.addView(top);

        mTitle = new TextView(getContext());
        mTitle.setLayoutParams(new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT));
        mTitle.setTextColor(Color.WHITE);
        mTitle.setTextSize(18);
        mTitle.setGravity(Gravity.CENTER);
        mTitle.setSingleLine(true);
        mTitle.setEllipsize(TruncateAt.MARQUEE);
        mTitle.setMarqueeRepeatLimit(-1);
        mTitle.setHorizontallyScrolling(true);
        top.addView(mTitle);

        mLeftView = createArrowButton(true);
        mLeftView.setOnClickListener(new OnClickListener() {
            @Override public void onClick(View v) {
                viewFlipper.setInAnimation(slideRightIn);
                viewFlipper.setOutAnimation(slideRightOut);
                viewFlipper.showPrevious();
                setPrevViewItem();
            }
        });
        top.addView(mLeftView);

        mRightView = createArrowButton(false);
        mRightView.setOnClickListener(new OnClickListener() {
            @Override public void onClick(View v) {
                viewFlipper.setInAnimation(slideLeftIn);
                viewFlipper.setOutAnimation(slideLeftOut);
                viewFlipper.showNext();
                setNextViewItem();
            }
        });
        top.addView(mRightView);
    }

    /** 產生左右箭頭按鈕(含按下態) */
    @SuppressWarnings("deprecation")
    private ImageButton createArrowButton(boolean isLeft) {
        ImageButton button = new ImageButton(getContext());
        String prefix = isLeft ? "image/left_arrow" : "image/right_arrow";

        Drawable normal = new BitmapDrawable(getResources(), BitmapFactory.decodeStream(
                CalendarView.class.getResourceAsStream(prefix + ".png")));
        Drawable pressed = new BitmapDrawable(getResources(), BitmapFactory.decodeStream(
                CalendarView.class.getResourceAsStream(prefix + "_pre.png")));

        StateListDrawable sld = new StateListDrawable();
        sld.addState(new int[]{ -android.R.attr.state_pressed }, normal);
        sld.addState(new int[]{ android.R.attr.state_pressed }, pressed);
        button.setBackgroundDrawable(sld);

        RelativeLayout.LayoutParams pp = new RelativeLayout.LayoutParams(
                ViewUtil.dip2px(getContext(), 25), ViewUtil.dip2px(getContext(), 22));
        pp.addRule(isLeft ? RelativeLayout.ALIGN_PARENT_LEFT : RelativeLayout.ALIGN_PARENT_RIGHT);
        pp.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        pp.setMargins(isLeft ? 20 : 0, 0, isLeft ? 0 : 20, 0);
        button.setLayoutParams(pp);
        return button;
    }

    /** 中間的星期標頭 */
    private void generateWeekGirdView() {
        GridView gridView = new GridView(getContext());
        gridView.setLayoutParams(new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        gridView.setNumColumns(7);
        gridView.setGravity(Gravity.CENTER_VERTICAL);
        gridView.setVerticalSpacing(1);
        gridView.setHorizontalSpacing(1);
        gridView.setBackgroundColor(Color.argb(0xff, 0xe3, 0xee, 0xf4));
        gridView.setAdapter(new WeekGridAdapter(getContext()));
        mMainLayout.addView(gridView);
    }

    /** 底部日期網格:一次準備三個月 */
    private void generateClaendarGirdView() {
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        Calendar c3 = Calendar.getInstance();
        c1.setTime(calStartDate.getTime());
        c2.setTime(calStartDate.getTime());
        c3.setTime(calStartDate.getTime());
        c1.add(Calendar.MONTH, -1);
        c3.add(Calendar.MONTH, 1);

        gView1 = new CalendarGridView(getContext());
        gAdapter1 = new CalendarGridViewAdapter(getContext(), c1, markDates);
        gView1.setAdapter(gAdapter1);
        gView1.setId(calLayoutID);

        gView2 = new CalendarGridView(getContext());
        gAdapter = new CalendarGridViewAdapter(getContext(), c2, markDates);
        gView2.setAdapter(gAdapter);
        gView2.setId(calLayoutID);

        gView3 = new CalendarGridView(getContext());
        gAdapter3 = new CalendarGridViewAdapter(getContext(), c3, markDates);
        gView3.setAdapter(gAdapter3);
        gView3.setId(calLayoutID);

        gView1.setOnTouchListener(this);
        gView2.setOnTouchListener(this);
        gView3.setOnTouchListener(this);

        if (viewFlipper.getChildCount() != 0) {
            viewFlipper.removeAllViews();
        }
        viewFlipper.addView(gView2);
        viewFlipper.addView(gView3);
        viewFlipper.addView(gView1);

        mTitle.setText(calStartDate.get(Calendar.YEAR) + "年"
                + NumberHelper.LeftPad_Tow_Zero(calStartDate.get(Calendar.MONTH) + 1) + "月");
    }

    private void setPrevViewItem() {
        iMonthViewCurrentMonth--;
        if (iMonthViewCurrentMonth == -1) {
            iMonthViewCurrentMonth = 11;
            iMonthViewCurrentYear--;
        }
        calStartDate.set(Calendar.DAY_OF_MONTH, 1);
        calStartDate.set(Calendar.MONTH, iMonthViewCurrentMonth);
        calStartDate.set(Calendar.YEAR, iMonthViewCurrentYear);
    }

    private void setNextViewItem() {
        iMonthViewCurrentMonth++;
        if (iMonthViewCurrentMonth == 12) {
            iMonthViewCurrentMonth = 0;
            iMonthViewCurrentYear++;
        }
        calStartDate.set(Calendar.DAY_OF_MONTH, 1);
        calStartDate.set(Calendar.MONTH, iMonthViewCurrentMonth);
        calStartDate.set(Calendar.YEAR, iMonthViewCurrentYear);
    }

    /** 把起始日推到該週的第一天(週一為開頭) */
    private void UpdateStartDateForMonth() {
        calStartDate.set(Calendar.DATE, 1);
        iMonthViewCurrentMonth = calStartDate.get(Calendar.MONTH);
        iMonthViewCurrentYear = calStartDate.get(Calendar.YEAR);

        int iDay = 0;
        if (calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.MONDAY < 0) {
            iDay = 6;
        } else {
            iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.MONDAY;
        }
        calStartDate.add(Calendar.DAY_OF_WEEK, -iDay);
    }

    /** 設定需要標注的日期集合 */
    public void setMarkDates(List<Date> markDates) {
        this.markDates.clear();
        this.markDates.addAll(markDates);
        gAdapter.notifyDataSetChanged();
        gAdapter1.notifyDataSetChanged();
        gAdapter3.notifyDataSetChanged();
    }

    public void setOnCalendarViewListener(OnCalendarViewListener listener) {
        this.mListener = listener;
    }

    @Override public boolean onDown(MotionEvent e) { return false; }

    @SuppressLint("ClickableViewAccessibility")
    @Override public boolean onTouch(View v, MotionEvent event) {
        return mGesture.onTouchEvent(event);
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false;

            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                viewFlipper.setInAnimation(slideLeftIn);
                viewFlipper.setOutAnimation(slideLeftOut);
                viewFlipper.showNext();
                setNextViewItem();
                return true;
            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                viewFlipper.setInAnimation(slideRightIn);
                viewFlipper.setOutAnimation(slideRightOut);
                viewFlipper.showPrevious();
                setPrevViewItem();
                return true;
            }
        } catch (Exception e) {
            // 忽略手勢計算過程中的異常
        }
        return false;
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        int pos = gView2.pointToPosition((int) e.getX(), (int) e.getY());
        LinearLayout cell = (LinearLayout) gView2.findViewById(pos + DEFAULT_ID);
        if (cell != null && cell.getTag() != null) {
            Date date = (Date) cell.getTag();
            calSelected.setTime(date);
            gAdapter.setSelectedDate(calSelected);
            gAdapter.notifyDataSetChanged();
            gAdapter1.setSelectedDate(calSelected);
            gAdapter1.notifyDataSetChanged();
            gAdapter3.setSelectedDate(calSelected);
            gAdapter3.notifyDataSetChanged();
            if (mListener != null) {
                mListener.onCalendarItemClick(this, date);
            }
        }
        return false;
    }

    @Override public void onAnimationEnd(Animation animation) { generateClaendarGirdView(); }
    @Override public void onAnimationRepeat(Animation animation) { }
    @Override public void onAnimationStart(Animation animation) { }
    @Override public void onLongPress(MotionEvent e) { }
    @Override public void onScroll(MotionEvent e1, MotionEvent e2, float dX, float dY) { return; }
    @Override public void onShowPress(MotionEvent e) { }
}

星期標頭的 Adapter

class WeekGridAdapter extends BaseAdapter {
    private final String[] titles = {"日", "一", "二", "三", "四", "五", "六"};
    private final Context mContext;

    public WeekGridAdapter(Context context) { this.mContext = context; }

    @Override public int getCount() { return titles.length; }
    @Override public Object getItem(int position) { return titles[position]; }
    @Override public long getItemId(int position) { return position; }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView week = new TextView(mContext);
        week.setLayoutParams(new LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        week.setGravity(Gravity.CENTER);
        week.setFocusable(false);
        week.setBackgroundColor(Color.TRANSPARENT);

        if (position == 6) {          // 週六
            week.setBackgroundColor(Color.argb(0xff, 0x52, 0x9b, 0xd0));
            week.setTextColor(Color.WHITE);
        } else if (position == 0) {   // 週日
            week.setBackgroundColor(Color.argb(0xff, 0xbc, 0x44, 0x45));
            week.setTextColor(Color.WHITE);
        } else {
            week.setTextColor(Color.BLACK);
        }
        week.setText(titles[position]);
        return week;
    }
}

日期格子的 Adapter

每個格子由「公曆數字 + 農曆/節氣文字」兩行組成,並依狀態切換背景色:今天、選中、已過去的日期、以及外部標注的日期各有不同配色。

class CalendarGridViewAdapter extends BaseAdapter {

    private static final int DEFAULT_ID = 0xff0000;

    private Calendar calStartDate = Calendar.getInstance();
    private Calendar calSelected  = Calendar.getInstance();
    private final Calendar calToday = Calendar.getInstance();

    private final List<Date> markDates;
    private final Context mContext;
    private final ArrayList<Date> titles = new ArrayList<Date>();

    public CalendarGridViewAdapter(Context context, Calendar cal, List<Date> dates) {
        this.mContext = context;
        this.calStartDate = cal;
        this.markDates = dates;
        buildDates();
    }

    /** 固定產生 42 格(6 週 × 7 天) */
    private void buildDates() {
        Calendar temp = (Calendar) calStartDate.clone();
        temp.set(Calendar.DATE, 1);
        int offset = temp.get(Calendar.DAY_OF_WEEK) - Calendar.MONDAY;
        if (offset < 0) offset = 6;
        temp.add(Calendar.DAY_OF_WEEK, -offset);

        for (int i = 1; i <= 42; i++) {
            titles.add(temp.getTime());
            temp.add(Calendar.DAY_OF_MONTH, 1);
        }
    }

    @Override public int getCount() { return titles.size(); }
    @Override public Object getItem(int position) { return titles.get(position); }
    @Override public long getItemId(int position) { return position; }

    public void setSelectedDate(Calendar cal) { this.calSelected = cal; }

    @SuppressWarnings("deprecation")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LinearLayout item = new LinearLayout(mContext);
        item.setId(position + DEFAULT_ID);
        item.setGravity(Gravity.CENTER);
        item.setOrientation(LinearLayout.VERTICAL);
        item.setBackgroundColor(Color.WHITE);

        Date myDate = getItem(position);
        item.setTag(myDate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(myDate);

        TextView textDay = new TextView(mContext);
        textDay.setGravity(Gravity.CENTER_HORIZONTAL);
        textDay.setText(String.valueOf(myDate.getDate()));
        item.addView(textDay, new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        TextView chineseDay = new TextView(mContext);
        chineseDay.setGravity(Gravity.CENTER_HORIZONTAL);
        chineseDay.setTextSize(9);
        chineseDay.setText(new CalendarUtil(cal).toString());
        item.addView(chineseDay, new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        if (equalsDate(calToday.getTime(), myDate)) {
            item.setBackgroundColor(Color.argb(0xff, 0x6d, 0xd6, 0x97));   // 今天
        }

        if (!CalendarUtil.compare(myDate, calToday.getTime())) {
            // 已過去的日期:整體淡化
            item.setBackgroundColor(Color.argb(0xff, 0xee, 0xee, 0xee));
            textDay.setTextColor(Color.argb(0xff, 0xc0, 0xc0, 0xc0));
            chineseDay.setTextColor(Color.argb(0xff, 0xc0, 0xc0, 0xc0));
        } else {
            chineseDay.setTextColor(Color.argb(0xff, 0x60, 0x3b, 0x07));
            if (equalsDate(calSelected.getTime(), myDate)) {
                item.setBackgroundColor(Color.argb(0xff, 0xdc, 0xe2, 0xff));  // 選中
            } else if (equalsDate(calToday.getTime(), myDate)) {
                item.setBackgroundColor(Color.argb(0xff, 0xfa, 0xed, 0xda));  // 今天
            }
        }

        // 外部標注的日期:以紅底強調
        if (markDates != null) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            for (Date date : markDates) {
                if (format.format(myDate).equals(format.format(date))) {
                    item.setBackgroundColor(Color.argb(0xff, 0xd3, 0x3a, 0x3a));
                    break;
                }
            }
        }
        return item;
    }

    @SuppressWarnings("deprecation")
    private boolean equalsDate(Date d1, Date d2) {
        return d1.getYear() == d2.getYear()
                && d1.getMonth() == d2.getMonth()
                && d1.getDate() == d2.getDate();
    }
}

日曆網格與農曆工具

CalendarGridView 只是把 GridView 的欄數、間距、內距設定好的薄包裝,讓每格寬度剛好等於螢幕寬度的七分之一。

CalendarUtil 是農曆換算的核心,做法是以 1900 年 1 月 31 日(農曆 1900 年正月初一)為基準,先算出目標日期與基準日相差的天數,再逐年、逐月扣減,剩下的餘數就是農曆的日。閏月與否、大小月則靠一份壓縮過的 LUNAR_INFO 位元表判斷。節氣(SolarTermsUtil)與公曆節日(GregorianUtil)則是查表比對,優先順序為:農曆節日 > 節氣 > 公曆節日 > 農曆日期。

由於這兩張對照表動輒數百筆常數,此處不逐行貼出,實作時直接沿用日曆換算的標準位元表即可,重點是理解「基準日 + 天數差 + 逐月扣減」這個演算法骨架。

輔助工具類

class NumberHelper {
    public static String LeftPad_Tow_Zero(int str) {
        return new java.text.DecimalFormat("00").format(str);
    }
}

public class ViewUtil {
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return Math.round(dipValue * scale);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return Math.round(pxValue / scale);
    }
}

怎麼用

先在 XML 中宣告控件:

<cc.util.android.view.CalendarView
    android:id="@+id/calendar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white" />

再在 Activity 中設定標注日期與點擊回呼:

CalendarView calendarView = (CalendarView) findViewById(R.id.calendar);

// 設定需要標記的日期
List<Date> markDates = new ArrayList<Date>();
markDates.add(new Date());
calendarView.setMarkDates(markDates);

// 設定點擊事件
calendarView.setOnCalendarViewListener(new CalendarView.OnCalendarViewListener() {
    @Override
    public void onCalendarItemClick(CalendarView view, Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA);
        Toast.makeText(MainActivity.this, format.format(date), Toast.LENGTH_SHORT).show();
    }
});

箭頭圖示資源

控件需要以下圖片,請放入 image 子目錄:

可再優化的地方

現版本的 getView 每次繪製都 new 出新的 LinearLayout 與 TextView,完全沒用到 convertView 複用,長列表滾動時容易卡頓;另外大量使用 Date.getYear() 這類已棄用的 API。若要 production 使用,建議改用 Calendar 取值並補上 ViewHolder 複用機制。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved