Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android 自定義日曆控件實作全過程詳解

編輯:Android 資訊

一、為什麼要自定義控件

有時候原生控件在外觀或功能上無法滿足需求,這時可以透過自定義控件來定制;還有一種情況是,原生控件雖然能透過繁瑣的程式碼勉強實現目標,但用自定義控件可以把這部分邏輯沉澱下來,顯著提升可複用性。

二、如何自定義控件

下面以我在 GitHub 上開源的 Android-CalendarView 專案為例,說明自定義控件的完整思路。專案中的自定義類別名為 CalendarView,它覆蓋了自定義控件時通常需要改寫的幾個關鍵方法。

構造函數

為了同時支援在 XML 版面中聲明和在 Java 程式碼中動態建立,一共實作了三個構造函數:

public CalendarView(Context context, AttributeSet attrs, int defStyle); public CalendarView(Context context, AttributeSet attrs); public CalendarView(Context context);

把初始化邏輯寫在參數最長的那個裡面,另外兩個直接委派給它即可:

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

構造函數裡主要做四件事。

1. 讀取自定義屬性

讀取版面檔案中可能設定的自定義屬性(這個日曆控件只定義了一個 mode 參數來表示顯示模式)。只要在 attrs.xml 中宣告過屬性,系統就會自動在 R.styleable 下生成對應的常量。

TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CalendarView); mode = typedArray.getInt(R.styleable.CalendarView_mode, Constant.MODE_SHOW_DATA_OF_THIS_MONTH);

同時需要在 res/values 下建立 attrs.xml 進行聲明:

<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="CalendarView"> <attr name="mode" format="integer" /> </declare-styleable> </resources>

2. 初始化繪製相關參數

比如字型顏色與尺寸、控件各部分的長寬與間距。

3. 初始化邏輯相關參數

對日曆來說,需要能判斷當前年月下每個單元格是否合法,以及合法時它代表的 day 是多少。在未指定年月之前,先用系統當前時間初始化:

/** * calculate the values of date[] and the legal range of index of date[] */ private void initial() { int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); int monthStart = -1; if(dayOfWeek >= 2 && dayOfWeek <= 7){ monthStart = dayOfWeek - 2; }else if(dayOfWeek == 1){ monthStart = 6; } curStartIndex = monthStart; date[monthStart] = 1; int daysOfMonth = daysOfCurrentMonth(); for (int i = 1; i < daysOfMonth; i++) { date[monthStart + i] = i + 1; } curEndIndex = monthStart + daysOfMonth; if(mode == Constant.MODE_SHOW_DATA_OF_THIS_MONTH){ Calendar tmp = Calendar.getInstance(); todayIndex = tmp.get(Calendar.DAY_OF_MONTH) + monthStart - 1; } }

其中 date[] 是長度為 42 的整型陣列——一個月最多需要 6 行來顯示(6 × 7 = 42)。curStartIndex 與 curEndIndex 界定了 date[] 的合法下標區間,分別對應該月第一天與最後一天在陣列中的位置。把「合法性判斷」抽成一個區間,後續的繪製與點擊命中判斷都能直接複用。

4. 綁定觸摸監聽器

掛上一個 OnTouchListener,負責處理使用者的點擊與滑動手勢。

onMeasure 方法

這個方法負責測量控件的寬與高。CalendarView 之所以必須改寫它,是因為某月第一天可能落在週一到週日的任何一天,每月天數也不盡相同,導致日曆的實際行數會變,高度自然隨之變化。因此要依當前年月即時計算高度(寬度直接取螢幕寬度即可):

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(screenWidth, View.MeasureSpec.EXACTLY); heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(measureHeight(), View.MeasureSpec.EXACTLY); setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec); }

其中 screenWidth 是構造函數中已取得的螢幕寬度,measureHeight() 則依年月算出所需高度,註解寫得比較詳細:

/** * calculate the total height of the widget */ private int measureHeight(){ /** * the weekday of the first day of the month, Sunday's result is 1 and Monday 2 and Saturday 7, etc. */ int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); /** * the number of days of current month */ int daysOfMonth = daysOfCurrentMonth(); /** * calculate the total lines, which equals to 1 (head of the calendar) + 1 (the first line) + n/7 + (n%7==0?0:1) * and n means numberOfDaysExceptFirstLine */ int numberOfDaysExceptFirstLine = -1; if(dayOfWeek >= 2 && dayOfWeek <= 7){ numberOfDaysExceptFirstLine = daysOfMonth - (8 - dayOfWeek + 1); }else if(dayOfWeek == 1){ numberOfDaysExceptFirstLine = daysOfMonth - 1; } int lines = 2 + numberOfDaysExceptFirstLine / 7 + (numberOfDaysExceptFirstLine % 7 == 0 ? 0 : 1); return (int) (cellHeight * lines); }

onDraw 方法

這個方法負責實際的繪製。其中 drawCircle 給定圓心與半徑畫圓,drawText 給定座標 x、y 畫文字。

/** * render */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); /** * render the head */ float baseline = RenderUtil.getBaseline(0, cellHeight, weekTextPaint); for (int i = 0; i < 7; i++) { float weekTextX = RenderUtil.getStartX(cellWidth * i + cellWidth * 0.5f, weekTextPaint, weekText[i]); canvas.drawText(weekText[i], weekTextX, baseline, weekTextPaint); } if(mode == Constant.MODE_CALENDAR){ for (int i = curStartIndex; i < curEndIndex; i++) { drawText(canvas, i, textPaint, "" + date[i]); } }else if(mode == Constant.MODE_SHOW_DATA_OF_THIS_MONTH){ for (int i = curStartIndex; i < curEndIndex; i++) { if(i < todayIndex){ if(data[date[i]]){ drawCircle(canvas, i, bluePaint, cellHeight * 0.37f); drawCircle(canvas, i, whitePaint, cellHeight * 0.31f); drawCircle(canvas, i, blackPaint, cellHeight * 0.1f); }else{ drawCircle(canvas, i, grayPaint, cellHeight * 0.1f); } }else if(i == todayIndex){ if(data[date[i]]){ drawCircle(canvas, i, bluePaint, cellHeight * 0.37f); drawCircle(canvas, i, whitePaint, cellHeight * 0.31f); drawCircle(canvas, i, blackPaint, cellHeight * 0.1f); }else{ drawCircle(canvas, i, grayPaint, cellHeight * 0.37f); drawCircle(canvas, i, whitePaint, cellHeight * 0.31f); drawCircle(canvas, i, blackPaint, cellHeight * 0.1f); } }else{ drawText(canvas, i, textPaint, "" + date[i]); } } } }

這裡有個容易踩的坑:繪製文字時,傳入的 x 是文字最左端的起始座標,但 y 並不是文字頂端的座標,而應該是 baseline(基線)。因此想把文字畫在某一區域的垂直中央,必須經過計算。我把這部分邏輯封裝到了 RenderUtil 中:

/** * get the baseline to draw between top and bottom in the middle */ public static float getBaseline(float top, float bottom, Paint paint){ Paint.FontMetrics fontMetrics = paint.getFontMetrics(); return (top + bottom - fontMetrics.bottom - fontMetrics.top) / 2; } /** * get the x position to draw around the middle */ public static float getStartX(float middle, Paint paint, String text){ return middle - paint.measureText(text) * 0.5f; }

自定義監聽器

控件需要對外提供一些監聽器,好在發生特定行為或互動時給外部一個處理入口。CalendarView 定義了兩個介面:

interface OnItemClickListener{ void onItemClick(int day); } interface OnRefreshListener{ void onRefresh(); }

先說明兩種模式。第一種是普通日曆模式,每個格子只顯示 day 數字;第二種是本月計劃完成情況模式,用圖形標示某一天是否完成了計劃(靈感來自「悅跑圈」,畫一個圈代表當天跑過步)。

OnRefreshListener 用於資料刷新後的回呼。兩種模式各有對應的刷新方法,且都會觸發回呼:refresh0 對應第一種模式,refresh1 對應第二種模式。

/** * used for MODE_CALENDAR * legal values of month: 1-12 */ @Override public void refresh0(int year, int month) { if(mode == Constant.MODE_CALENDAR){ selectedYear = year; selectedMonth = month; calendar.set(Calendar.YEAR, selectedYear); calendar.set(Calendar.MONTH, selectedMonth - 1); calendar.set(Calendar.DAY_OF_MONTH, 1); initial(); invalidate(); if(onRefreshListener != null){ onRefreshListener.onRefresh(); } } } /** * used for MODE_SHOW_DATA_OF_THIS_MONTH * the index 1 to 31(big month), 1 to 30(small month), 1 - 28(Feb of normal year), 1 - 29(Feb of leap year) * is better to be accessible in the parameter data, illegal indexes will be ignored with default false value */ @Override public void refresh1(boolean[] data) { /** * the month and year may change (eg. Jan 31st becomes Feb 1st after refreshing) */ if(mode == Constant.MODE_SHOW_DATA_OF_THIS_MONTH){ calendar = Calendar.getInstance(); selectedYear = calendar.get(Calendar.YEAR); selectedMonth = calendar.get(Calendar.MONTH) + 1; calendar.set(Calendar.DAY_OF_MONTH, 1); for(int i = 1; i <= daysOfCurrentMonth(); i++){ if(i < data.length){ this.data[i] = data[i]; }else{ this.data[i] = false; } } initial(); invalidate(); if(onRefreshListener != null){ onRefreshListener.onRefresh(); } } }

OnItemClickListener 則用來回應「點擊了日曆上某一天」這個事件。點擊的判定在 onTouch 中完成:只有在同一位置依序收到 ACTION_DOWN 與 ACTION_UP 兩個事件,才算一次有效點擊。

@Override public boolean onTouch(View v, MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if(coordIsCalendarCell(y)){ int index = getIndexByCoordinate(x, y); if(isLegalIndex(index)) { actionDownIndex = index; } } break; case MotionEvent.ACTION_UP: if(coordIsCalendarCell(y)){ int actionUpIndex = getIndexByCoordinate(x, y); if(isLegalIndex(actionUpIndex)){ if(actionDownIndex == actionUpIndex){ actionDownIndex = -1; int day = date[actionUpIndex]; if(onItemClickListener != null){ onItemClickListener.onItemClick(day); } } } } break; } return true; }

三、關於這個日曆控件

效果圖如下,分別是普通日曆模式與本月計劃完成情況模式:

需要說明的是,CalendarView 只包含日曆標頭與下方的日期格,圖中上方那部分是專案裡的其他控件,僅用來示範一種使用方式,你完全可以自定義那部分的樣式。

另外,日曆標頭的文字支援多種格式,比如週一可以顯示為「一」、「周一」、「星期一」或「Mon」。還有其他控制樣式的介面,詳見 GitHub 專案首頁。

GitHub 專案首頁:Android-CalendarView

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