編輯: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); }
構造函數裡主要做四件事。
讀取版面檔案中可能設定的自定義屬性(這個日曆控件只定義了一個 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>
比如字型顏色與尺寸、控件各部分的長寬與間距。
對日曆來說,需要能判斷當前年月下每個單元格是否合法,以及合法時它代表的 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[] 的合法下標區間,分別對應該月第一天與最後一天在陣列中的位置。把「合法性判斷」抽成一個區間,後續的繪製與點擊命中判斷都能直接複用。
掛上一個 OnTouchListener,負責處理使用者的點擊與滑動手勢。
這個方法負責測量控件的寬與高。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); }
這個方法負責實際的繪製。其中 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
打造一個具備平滑滾動效果的 Android 歌詞控件
馬上就要畢業了,前段時間一直忙於畢業設計和論文(蛋疼連著菊花疼),做的是一個 Android 音樂播放器。今天特意抽出其中一塊功能來寫這篇博客——歌詞的顯示。 看看 QQ
從系統啟動到 App 運行:Android 底層原理全景梳理
前言 好久沒有認真寫過部落格了,突然意識到許多學過的知識若不及時總結消化,終究無法真正內化為自己的東西。而寫部落格的好處之一,就是能在梳理的過程中發現當初學習時未曾留意的
深入理解 Android View 繪制流程
窗口與 DecorView 在 Android 中,Activity 的界面由 Window 承載。PhoneWindow 是 Window 的具體實現,而 DecorV
深入 Android Activity 啟動流程:從 main() 一路追到 View 繪製
本文透過 DDMS 對一個簡單 Demo 做除錯標記,暫停主執行緒後觀察呼叫堆疊,逐層拆解 Activity 從被啟動到畫面真正呈現的完整路徑。一、起點:Activity