最近項(xiàng)目需要日歷效果凹嘲,考慮用第三方的反而不太適合設(shè)計(jì)需求师倔,修改復(fù)雜,與其這樣不入自己重新寫一個(gè)干凈的控件周蹭。雖不是什么牛逼控件趋艘,但是也需要我們能按照設(shè)計(jì)自己寫出來。在此記錄一下實(shí)現(xiàn)思路凶朗。
效果圖:
實(shí)現(xiàn)思路
- 頭部是一個(gè)自定義組合控件瓷胧;
- 顯示一周的日期部分用GridView 更加方便更新;
- 切換月的部分是一個(gè)自定義PopupWindow棚愤;
- GridView選中效果搓萧;
- GridView根據(jù)手勢GestureDetector監(jiān)聽左右滑動(dòng);
- 核心其實(shí)還是Calendar類,根據(jù)這個(gè)類我們可以獲取制定日期一周的日期集合瘸洛、可以獲取制定日期一月的日期集合等等揍移;
- 根據(jù)陽歷日期獲取陰歷日期
使用
// xml布局引用
<com.wzh.calendar.view.DataView
android:id="@+id/week"
android:layout_width="match_parent"
android:background="@color/color_ffffff"
android:layout_height="wrap_content">
</com.wzh.calendar.view.DataView>
// 代碼中,自定義回調(diào)監(jiān)聽選中的日期
dataView = (DataView) findViewById(R.id.week);
dataView.setOnSelectListener(new DataView.OnSelectListener() {
@Override
public void onSelected(DateEntity date) {
info.setText("日期:"+ date.date+"\n"+
"周幾:"+ date.weekName+"\n"+
"今日:"+ date.isToday+"\n"+
"時(shí)間戳:"+ date.million+"\n");
Log.e("wenzhiao--------------",date.toString());
}
});
//需要傳遞此種格式的日期货矮,不傳默認(rèn)是獲取今日的日期
dataView.getData("2017-04-19");
實(shí)現(xiàn)整體邏輯
回調(diào)的日期信息封裝成一個(gè)實(shí)體類DateEntity:
public class DateEntity {
public long million ; //時(shí)間戳
public String weekName ; //周幾
public int weekNum ; //一周中第幾天羊精,非中式
public String date ; //日期
public boolean isToday ; //是否今天
public String day ; //天
public String luna ; //陰歷
@Override
public String toString() {
return "DateEntity{" +
"million=" + million +
", weekName='" + weekName + '\'' +
", weekNum=" + weekNum +
", date='" + date + '\'' +
", isToday=" + isToday +
", day='" + day + '\'' +
", luna='" + luna + '\'' +
'}';
}
}
封裝的日期獲取的工具類:
package com.wzh.calendar.utils;
import com.wzh.calendar.bean.DateEntity;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class DataUtils {
public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static int selectPosition =-1;
public static int getSelectPosition() {
return selectPosition;
}
/**
*
* 獲取當(dāng)前日期一周的日期
* @param date
* @return
*/
public static ArrayList<DateEntity> getWeek(String date){
ArrayList<DateEntity> result = new ArrayList<>();
Calendar cal =Calendar.getInstance();
try {
cal.setTime(dateFormat.parse(date));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); //獲取本周一的日期
for (int i = 0; i < 7; i++) {
DateEntity entity = new DateEntity();
entity.date = getValue(cal.get(cal.YEAR))+"-"+getValue(cal.get(cal.MONTH)+1)+"-"+getValue(cal.get(cal.DATE));
entity.million = cal.getTimeInMillis() ;
entity.day = getValue(cal.get(cal.DATE));
entity.weekNum = cal.get(Calendar.DAY_OF_WEEK);
entity.weekName = getWeekName(entity.weekNum);
entity.isToday = isToday(entity.date);
cal.add(Calendar.DATE, 1);
result.add(entity);
}
return result ;
}
/**
* 獲取當(dāng)前日期一月的日期
* @param date
* @return
*/
public static ArrayList<DateEntity> getMonth(String date){
ArrayList<DateEntity> result = new ArrayList<>();
Calendar cal =Calendar.getInstance();
try {
cal.setTime( new SimpleDateFormat("yyyy-MM").parse(date));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int max = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = 1; i <=max; i++) {
DateEntity entity = new DateEntity();
entity.date = getValue(cal.get(cal.YEAR))+"-"+getValue(cal.get(cal.MONTH)+1)+"-"+getValue(cal.get(cal.DATE));
entity.million = cal.getTimeInMillis() ;
entity.weekNum = cal.get(Calendar.DAY_OF_WEEK);
entity.day = getValue(cal.get(cal.DATE));
entity.weekName = getWeekName(entity.weekNum);
entity.isToday = isToday(entity.date);
entity.luna = getLuna(entity.date);
cal.add(Calendar.DATE, 1);
result.add(entity);
}
//為了用空的值填補(bǔ)第一個(gè)之前的日期
//先獲取在本周內(nèi)是周幾
int weekNum = result.get(0).weekNum -1 ;
for (int j = 0 ;j<weekNum;j++){
DateEntity entity = new DateEntity();
result.add(0,entity);
}
for (int i = 0; i <result.size(); i++) {
if (date.equals(result.get(i).date)){
selectPosition = i ;
}
}
return result ;
}
/**
* 根據(jù)美式周末到周一 返回
* @param weekNum
* @return
*/
private static String getWeekName(int weekNum) {
String name = "" ;
switch (weekNum) {
case 1:
name = "星期日";
break;
case 2:
name = "星期一";
break;
case 3:
name = "星期二";
break;
case 4:
name = "星期三";
break;
case 5:
name = "星期四";
break;
case 6:
name = "星期五";
break;
case 7:
name = "星期六";
break;
default:
break;
}
return name;
}
/**
* 是否是今天
* @param sdate
* @return
*/
public static boolean isToday(String sdate){
boolean b = false;
Date time = null ;
try {
time = dateFormat.parse(sdate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Date today = new Date();
if(time != null){
String nowDate = dateFormater.get().format(today);
String timeDate = dateFormater.get().format(time);
if(nowDate.equals(timeDate)){
b = true;
}
}
return b;
}
/**
* 個(gè)位數(shù)補(bǔ)0操作
* @param num
* @return
*/
public static String getValue(int num){
return String.valueOf(num>9?num:("0"+num));
}
private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
/**
* 獲取系統(tǒng)當(dāng)前日期
*/
public static String getCurrDate(String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format);
Date curDate = new Date(System.currentTimeMillis());//獲取當(dāng)前時(shí)間
String str = formatter.format(curDate);
return str;
}
/**
* 格式化日期
*/
public static String formatDate(String date ,String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format);
Date curDate = null;//獲取當(dāng)前時(shí)間
try {
curDate = formatter.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
String str = formatter.format(curDate);
return str;
}
/**
* 切換周的時(shí)候用
* 獲取前/后 幾天的一個(gè)日期
* @param currentData
* @param dayNum
* @return
*/
public static String getSomeDays(String currentData,int dayNum){
Calendar c = Calendar.getInstance();
//過去七天
try {
c.setTime(DataUtils.dateFormat.parse(currentData));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, dayNum);
Date d = c.getTime();
String day = DataUtils.dateFormat.format(d);
return day ;
}
/**
* 獲取前/后 幾個(gè)月的一個(gè)日期 切換月的時(shí)候用
* @param currentData
* @param monthNum
* @return
*/
public static String getSomeMonthDay(String currentData,int monthNum){
Calendar c = Calendar.getInstance();
try {
c.setTime(new SimpleDateFormat("yyyy-MM").parse(currentData));
} catch (ParseException e) {
e.printStackTrace();
}
c.set(Calendar.MONTH, c.get(Calendar.MONTH) +monthNum);
Date day = c.getTime();
return new SimpleDateFormat("yyyy-MM-dd").format(day);
}
/**
* 獲取陰歷
* @param date
* @return
*/
public static String getLuna(String date){
Calendar today = Calendar.getInstance();
try {
today.setTime(Lunar.chineseDateFormat.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
return new Lunar(today).toString() ;
}
}
這里有個(gè)地方需要注意一下,因?yàn)槲覀円粋€(gè)月第一天是周幾不確定囚玫,顯示GridView的時(shí)候第一天的position也不確定喧锦,但是我們可以根據(jù)前面少了幾天再添加上空對象即可:
//為了用空的值填補(bǔ)第一個(gè)之前的日期
//先獲取在本周內(nèi)是周幾
int weekNum = result.get(0).weekNum -1 ;
for (int j = 0 ;j<weekNum;j++){
DateEntity entity = new DateEntity();
result.add(0,entity);
}
還有一個(gè)獲取陰歷日期的工具類,比較復(fù)雜抓督,所以直接從網(wǎng)上找了一個(gè)燃少,這里就不貼了。
剩下的就是去寫布局铃在、自定義PopupWindow了阵具,這些應(yīng)該是沒什么難度吧。關(guān)于GridView選中定铜,原理就是在Adapter里面設(shè)置一個(gè)選中方法:
private int selectedPosition = -1;// 選中的位置
public void setSelectedPosition(int position) {
selectedPosition = position;
notifyDataSetChanged();
}
...
在Adapter的getView(int position, View convertView, ViewGroup parent)
方法去判斷 position是否和selectedPosition 是否相等阳液,相等就表示選中了,可以修改背景揣炕、字體顏色等等
...
當(dāng)然在用到Adapter的地方也要調(diào)用setSelectedPosition方法
具體怎么使用可以參考里面的代碼帘皿。
關(guān)于GrdiView左右滑動(dòng)的判斷(關(guān)鍵代碼片段):
private GestureDetector gestureDetector;
//初始化
gestureDetector = new GestureDetector(context,onGestureListener);
/**
* 手勢監(jiān)聽是否是左右滑動(dòng),這里認(rèn)為滑動(dòng)距離超過100就算左右滑動(dòng)
*/
private GestureDetector.OnGestureListener onGestureListener =
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
float x = e2.getX() - e1.getX();
float y = e2.getY() - e1.getY();
if (x > 100) {
doResult(RIGHT);
} else if (x < -100) {
doResult(LEFT);
}
return true;
}
};
public void doResult(int action) {
switch (action) {
case RIGHT:
date = DataUtils.getSomeMonthDay(date,-1);
adapter.setData(DataUtils.getMonth(date));
adapter.setDateString(date);
adapter.setSelectedPosition(DataUtils.getSelectPosition());
currentDateTv.setText("當(dāng)前月份:"+DataUtils.formatDate(date,"yyyy-MM"));
Log.e("wenzihao","go right");
break;
case LEFT:
date = DataUtils.getSomeMonthDay(date,+1);
adapter.setData(DataUtils.getMonth(date));
adapter.setDateString(date);
adapter.setSelectedPosition(DataUtils.getSelectPosition());
currentDateTv.setText("當(dāng)前月份:"+DataUtils.formatDate(date,"yyyy-MM"));
Log.e("wenzihao","go left");
break;
}
}
...設(shè)置手勢給gridview
gridView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
最后就是點(diǎn)擊PopupWindow的時(shí)候自定義回調(diào)方法把選中日期帶過去即可畸陡。
好了鹰溜,其他的代碼也不貼了,關(guān)鍵點(diǎn)就那么點(diǎn)丁恭,沒啥太大難度曹动,感覺主要還是考驗(yàn)大家的基本功吧。
這么一個(gè)自定義日歷控件就寫好了牲览,是不是很簡單感覺墓陈,希望能夠?qū)Υ蠹矣袉l(fā)和幫助,可以靈活自定義出設(shè)計(jì)產(chǎn)品需要的各種控件第献。
最后附上項(xiàng)目地址:github地址