当前位置: 移动技术网 > 移动技术>移动开发>Android > Android自定义日历控件实例详解

Android自定义日历控件实例详解

2019年07月24日  | 移动技术网移动技术  | 我要评论

为什么要自定义控件

有时,原生控件不能满足我们对于外观和功能的需求,这时候可以自定义控件来定制外观或功能;有时,原生控件可以通过复杂的编码实现想要的功能,这时候可以自定义控件来提高代码的可复用性。

如何自定义控件

下面我通过我在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[]数组的合法下标区间,即前者表示该月的第一天在date[]数组的下标,后者表示该月的最后一天在date[]数组的下标。

4 绑定了一个ontouchlistener监听器

监听控件的触摸事件。

onmeasure方法

该方法对控件的宽和高进行测量。calendarview覆盖了view类的onmeasure()方法,因为某个月的第一天可能是星期一到星期日的任何一个,而且每个月的天数不尽相同,因此日历控件的行数会有多变化,也导致控件的高度会有变化。因此需要根据当前的年月计算控件显示的高度(宽度设为屏幕宽度即可)。实现如下。

@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表示开始位置的x坐标(文字最左端),这个y却不是文字最顶端的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提供了两个接口,onrefreshlistener和onitemclicklistener,均为自定义的接口。onitemclick只传了day一个参数,年和月可通过calendarview对象的getyear和getmonth方法获取。

interface onitemclicklistener{
 void onitemclick(int day);
}
interface onrefreshlistener{
 void onrefresh();
}

先介绍一下两种mode,calendarview提供了两种模式,第一种普通日历模式,日历每个位置简单显示了day这个数字,第二种本月计划完成情况模式,绘制了一些图形来表示本月的某一天是否完成了计划(模仿自悦跑圈,用一个圈表示本日跑了步)。

onrefreshlistener用于刷新日历数据后进行回调。两种模式定义了不同的刷新方法,都对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;
}

关于该日历控件

日历控件demo效果图如下,分别为普通日历模式和本月计划完成情况模式。

需要说明的是calendarview控件部分只包括日历头与下面的日历,该控件上方的是其他控件,这里仅用作展示一种使用方法,你完全可以自定义这部分的样式。

此外,日历头的文字支持多种选择,比如周一有四种表示:一、周一、星期一、mon。此外还有其他一些控制样式的接口,详情见源码:。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网