Android 自定义实现日历
- 开发工具AndroidStudio,使用组件GridView
开发工具AndroidStudio,使用组件GridView
实现步骤以及原理
- 通过Calendar获取当前年月日
- 获取指定年月的天数
- 得到当月一号是星期几
- 获取日期对象的列表数据:当月天数加上当月1号星期几之前的空白数据(比如1号是星期3,那么日期列表数据之前添加三个数据)
- 设置GridView的适配器
具体实现
- 用Calendar对象获取日期
Calendar calendar = Calendar.getInstance(); currYear = calendar.get(Calendar.YEAR); currMouth = calendar.get(Calendar.MONTH);
- 获取对应年月的天数
private int getMonthLastDay(int year, int month) {
Calendar a = Calendar.getInstance();
a.set(Calendar.YEAR, year);
a.set(Calendar.MONTH, month - 1);
a.set(Calendar.DATE, 1);//把日期设置为当月第一天
a.roll(Calendar.DATE, -1);//日期回滚一天,也就是最后一天
return a.get(Calendar.DATE);
}
- 一号是星期几
Calendar calendar = Calendar.getInstance();
int currYear = calendar.get(Calendar.YEAR);
int currMouth = calendar.get(Calendar.MONTH) + 1;
int currDay = calendar.get(Calendar.DAY_OF_MONTH);
calendar.set(year, mouth - 1, 0);
int i1 = calendar.get(Calendar.DAY_OF_WEEK);//这就是星期几
- 得到日期数据列表
public void requestData() {
last_state = 0;
state_count = 0;
ArrayList datas = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
int currYear = calendar.get(Calendar.YEAR);
int currMouth = calendar.get(Calendar.MONTH) + 1;
int currDay = calendar.get(Calendar.DAY_OF_MONTH);
calendar.set(year, mouth - 1, 0);
int i1 = calendar.get(Calendar.DAY_OF_WEEK);
if (i1 > 6)//如果大于6天,也就是一个星期的天数,就不用添加,否则显示一行空白
i1 = 0;
for (int i = 0; i < i1; i++) {
datas.add(new DateInfo(true));
}
for (int i = 0; i < getMonthLastDay(year, mouth); i++) {
DateInfo data = new DateInfo(year, mouth, i + 1);
if (currYear == year && currMouth == mouth && currDay == i + 1)
data.setToday(true);
data.setState(new Random().nextInt(4));//设置这一天的状态的
if (last_state == 0) {
last_state = data.getState();
state_count = 1;
} else if (last_state == data.getState()) {
++state_count;
datas.get(i + i1 - 1).setState_count(state_count);
data.setState_count(state_count);
} else {
last_state = data.getState();
state_count = 1;
}
datas.add(data);
}
}
- 最后继承自BaseAdapter,设置GridView的适配器