如今網上有不少自定義view實現日曆的demo,今天講一講如何本身實現這個自定義view。javascript
看一下最終效果圖:java
在這個自定義view中,我使用了各類奇技淫巧的方法來實現這個日曆,真是費盡心思。廢話少說,開始進坑。ide
頭部是一個textview,顯示年份和月份,而後下邊一行是星期幾,這兩行能夠固定住,不隨月份切換而進出屏幕。工具
再下邊就是咱們自定義view 的主角,每月的天數。目前規定是星期日爲每星期第一天。上個月的天數填充滿第一行,下個月的前幾天填充完最後一行,顏色設置爲灰色,本月日期中的週一至週五設置爲紅色,週六週日設置爲青色,特殊日期設置爲綠色,而且在右上角填充特殊標識符,用四分之三的圓弧包裹(上個月和下個月的日期沒有)。佈局
此處還有個小細節,每個月的總行數會不斷改變,可是view的總高度並未改變,因此視覺效果會不同。ui
public MyCalendar(Context context) {
super(context);
}
public MyCalendar(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}複製代碼
主要是實現上面兩個構造方法,第一個是用來在java代碼中使用的,第二個是用來在xml佈局文件中使用的。this
目前接口共有下面幾個,setDate(CustomDate customDate),setWeekendHighLight(boolean b),setSpecialDay(int[] ints)spa
其中第一個是必需要設置的,不然是不會顯示任何東西,第二個設置的是否週末高亮,第三個設置的是特殊顯示的日期,第四個是設置是否能夠點擊前一個月或者後一個月的日期,默認爲不設置,後期能夠根據本身需求增長其餘接口。3d
/** * 暴露接口,設置日期 * * @param customDate */
public void setDate(CustomDate customDate) {
Log.d(TAG, customDate.toString());
this.date = customDate;
firstDayOfWeek = date.getFirstDayOfWeek();
Log.d(TAG, (date.getMonth() + 1) + "月1號是星期" + firstDayOfWeek);
lastDayOfWeek = date.getLastDayOfWeek();
lineCount = calculateLineNum() + 1;
lastMonthTotalDays = date.getLastMonthDays();
}
/** * 暴露接口,設置是否週末高亮 * * @param b */
public void setWeekendHighLight(boolean b) {
this.weekendHighlight = b;
}
public void setSpecialDay(int[] ints) {
this.specialDays = ints;
}
/** * 暴露接口,設置是否能夠點擊前一個月和後一個月的日期 * * @param b */
public void setCanClickNextOrPreMonth(boolean b) {
this.canClickNextOrPreMonth = b;
}複製代碼
在這裏說明一下計算顯示行數的方法,首先要注意咱們獲取的星期數與實際的星期幾會有一個增長一天的問題,也就是當前是星期4,那麼你獲取的int將會是5.code
/** * 得到應該設置爲多少行 * * @return */
private int calculateLineNum() {
monthDaySum = date.getTotalDayOfMonth();
return (firstDayOfWeek - 1 + monthDaySum) / 7;
}複製代碼
咱們將第一天是星期幾減去一後加上這個月總共多少天,就能夠得到最後一天是在什麼位置,而後除以七取商的整數部分,而後在進一法便可得到應該顯示多少行。
onSizechanged方法中已經能夠得到顯示的尺寸了,此時咱們須要作一些工做:
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
this.viewWidth = w;
this.viewHeight = h;
Log.d(TAG, "onSizeChanged" + w + h);
cutGrid();
init();
setCellDay();
}複製代碼
首先是將寬和高引入進來,方便後邊使用。
cutGrid()方法是將區域分割爲行X列的格式。
init()方法初始化了一些畫筆。
setCellDay()方法將每個月的天對應過到座標上。
首先看一下cutGrid()方法:
/** * 切分爲天天 */
private void cutGrid() {
cellWidth = (float) viewWidth / ROW_COUNT;
cellHeight = (float) viewHeight / lineCount;
this.radius = Math.min(cellWidth / 2, cellHeight / 2);
for (int i = 0; i < lineCount; i++) {
for (int j = 0; j < ROW_COUNT; j++) {
points.add(new PointF(cellWidth * j + cellWidth / 2, cellHeight * i + cellHeight / 2));
}
}
}複製代碼
cellWidth是天天的寬度,其中ROW_COUNT是一個常量7,表示每週7天;cellHeight是每行的高度,linecount是一個變量,須要咱們根據日期計算,後邊會說到;radius是咱們繪製區域的半徑,這個值是咱們取寬度和高度中較小的值的一半。而後咱們將每一個方格中心座標點利用雙重循環放入一個List
整個view被分割爲如上的形狀。
下面來看一下init()方法:
private void init() {
circlePaint = new Paint();
circlePaint.setStyle(Paint.Style.STROKE);
circlePaint.setAntiAlias(true);
circlePaint.setColor(Color.BLUE);
textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setColor(Color.BLACK);
textPaint.setTextSize(radius / 2);
selectPaint = new Paint();
selectPaint.setColor(Color.YELLOW);
selectPaint.setAlpha(10);
selectPaint.setAntiAlias(true);
selectPaint.setStyle(Paint.Style.STROKE);
selectTextPaint = new Paint();
selectTextPaint.setColor(Color.WHITE);
selectTextPaint.setAntiAlias(true);
selectTextPaint.setTextSize(radius / 2);
selectTextPaint.setStyle(Paint.Style.FILL);
}複製代碼
基本都是畫筆工具。
而後是setAllDays()方法:
/** * 設置總共顯示多少天,天天的狀態 */
private void setCellDay() {
cellDays = new CellDay[lineCount * ROW_COUNT];
for (int i = 0, length = cellDays.length; i < length; i++) {
cellDays[i] = new CellDay();
cellDays[i].setPointX(points.get(i).x);
cellDays[i].setPointY(points.get(i).y);
if (firstDayOfWeek > 1 && i < firstDayOfWeek - 1) {
cellDays[i].setDayState(DayState.LASTMONTH);
cellDays[i].setDate(String.valueOf(lastMonthTotalDays - firstDayOfWeek + i + 2));
cellDays[i].setCustomDate(new CustomDate(
date.getYear(), date.getMonth() - 1, lastMonthTotalDays - firstDayOfWeek + i + 2));
}
if (i >= firstDayOfWeek - 1 && i < monthDaySum + firstDayOfWeek - 1) {
cellDays[i].setDayState(CURRENTMONTH);
cellDays[i].setDate(String.valueOf(i + 2 - firstDayOfWeek));
cellDays[i].setCustomDate(new CustomDate(
date.getYear(), date.getMonth(), i - firstDayOfWeek + 2));
//設置週末高亮
if (weekendHighlight) {
if (i % 7 == 0 || i % 7 == 6) {
cellDays[i].setDayState(WEEKEND);
}
}
}
if (i >= monthDaySum + firstDayOfWeek - 1) {
cellDays[i].setDayState(NEXTMONTH);
cellDays[i].setDate(String.valueOf(i - monthDaySum - firstDayOfWeek + 2));
cellDays[i].setCustomDate(new CustomDate(
date.getYear(), date.getMonth() + 1, i - monthDaySum - firstDayOfWeek + 2));
}
for (int j = 0, s = specialDays.length; j < s; j++) {
if (specialDays[j] + firstDayOfWeek - 2 == i) {
cellDays[i].setDayState(SPECIALDAY);
}
}
}
}複製代碼
在這裏咱們用到了一個自定的類-CellDay。
CellDay有如下幾個字段
private String date;
private DayState dayState;
private CustomDate customDate;
private float pointX;
private float pointY;
private boolean isSelected;複製代碼
其中能夠設置多種狀態,用法和SPECIALDAY基本同樣。
public class CustomDate {
private Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
private int year;
private int month;
private int day;
private int dayOfWeek;
public CustomDate() {
}
/** * 獲取當前的日期 * @return */
public CustomDate getCurrentDate() {
this.year = calendar.get(Calendar.YEAR);
this.month = calendar.get(Calendar.MONTH);
this.day = calendar.get(Calendar.DAY_OF_MONTH);
this.dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
return new CustomDate(year, month, day);
}
public CustomDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
calendar.set(year, month, day);
dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
}
/** * 獲取上個月的天數 * @return */
public int getLastMonthDays() {
return this.getDaysOfMonth(this.year, this.month - 1);
}
/** * 獲取第一天是星期幾 * * @return */
public int getFirstDayOfWeek() {
calendar.set(this.year, this.month, 1);
return calendar.get(Calendar.DAY_OF_WEEK);
}
/** * 獲取最後一天是星期幾 * * @return */
public int getLastDayOfWeek() {
calendar.set(this.year, this.month, getTotalDayOfMonth());
return calendar.get(Calendar.DAY_OF_WEEK);
}
/** * 獲取這個月總共的天數 * @return */
public int getTotalDayOfMonth() {
return this.getDaysOfMonth(year, month);
}
public int getTotalWeekOfMonth() {
return calendar.getMaximum(Calendar.WEEK_OF_MONTH);
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getDayOfWeek() {
return dayOfWeek;
}
public void setDayOfWeek(int dayOfWeek) {
this.dayOfWeek = dayOfWeek;
}
@Override
public String toString() {
return "CustomDate{" +
"year=" + year +
", month=" + (getMonth() + 1) +
", day=" + day +
", dayOfWeek=" + dayOfWeek +
'}';
}
/** * 獲取年中每個月的天數 * @param year * @param month * @return */
private int getDaysOfMonth(int year, int month) {
if (month > 11) {
month = 0;
year += 1;
} else if (month < 0) {
month = 11;
year -= 1;
}
int[] arr = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int daysOfMonth = 0;
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
arr[1] = 29;
}
daysOfMonth = arr[month];
return daysOfMonth;
}
}複製代碼
註釋中對每一個方法的說明已經很是清晰了。
下一節將介紹如何繪製和分發touch事件。