android gridview控件使用详解_Android开发实现自定义日历、日期选择控件
點擊上方藍字關注???
來源:?wenzhihao123
https://www.jianshu.com/p/a2f102c728ce
前言
最近項目需要日歷效果,考慮用第三方的反而不太適合設計需求,修改復雜,與其這樣不入自己重新寫一個干凈的控件。雖不是什么牛逼控件,但是也需要我們能按照設計自己寫出來。在此記錄一下實現思路。
效果圖:
詳解
實現思路
- 頭部是一個自定義組合控件; 
- 顯示一周的日期部分用GridView 更加方便更新; 
- 切換月的部分是一個自定義PopupWindow; 
- GridView選中效果; 
- GridView根據手勢GestureDetector監聽左右滑動; 
- 核心其實還是Calendar類,根據這個類我們可以獲取制定日期一周的日期集合、可以獲取制定日期一月的日期集合等等; 
- 根據陽歷日期獲取陰歷日期 
使用:
// xml布局引用 android:id="@+id/week"
 android:layout_width="match_parent"
 android:background="@color/color_ffffff"
 android:layout_height="wrap_content">// 代碼中,自定義回調監聽選中的日期
dataView = (DataView) findViewById(R.id.week);
dataView.setOnSelectListener(new DataView.OnSelectListener() {
 @Overridepublic void onSelected(DateEntity date) {
 info.setText("日期:"+ date.date+"\n"+"周幾:"+ date.weekName+"\n"+"今日:"+ date.isToday+"\n"+"時間戳:"+ date.million+"\n");
 Log.e("wenzhiao--------------",date.toString());
 }
 });//需要傳遞此種格式的日期,不傳默認是獲取今日的日期
dataView.getData("2017-04-19");
實現整體邏輯
回調的日期信息封裝成一個實體類DateEntity:
public class DateEntity {public long million ; //時間戳public String weekName ; //周幾public int weekNum ; //一周中第幾天,非中式public String date ; //日期public boolean isToday ; //是否今天public String day ; //天public String luna ; //陰歷@Overridepublic 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;
 }/**
 *
 * 獲取當前日期一周的日期
 * @param date
 * @return
 */public static ArrayListgetWeek(String date){
 ArrayList 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 ;
 }/**
 * 獲取當前日期一月的日期
 * @param date
 * @return
 */public static ArrayListgetMonth(String date){
 ArrayList 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);
 }//為了用空的值填補第一個之前的日期//先獲取在本周內是周幾int weekNum = result.get(0).weekNum -1 ;for (int j = 0 ;j DateEntity entity = new DateEntity();
 result.add(0,entity);
 }for (int i = 0; i if (date.equals(result.get(i).date)){
 selectPosition = i ;
 }
 }return result ;
 }/**
 * 根據美式周末到周一 返回
 * @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;
 }/**
 * 個位數補0操作
 * @param num
 * @return
 */public static String getValue(int num){return String.valueOf(num>9?num:("0"+num));
 }private final static ThreadLocal dateFormater = new ThreadLocal() {
 @Overrideprotected SimpleDateFormat initialValue() {return new SimpleDateFormat("yyyy-MM-dd");
 }
 };/**
 * 獲取系統當前日期
 */public static String getCurrDate(String format) {
 SimpleDateFormat formatter = new SimpleDateFormat(format);
 Date curDate = new Date(System.currentTimeMillis());//獲取當前時間
 String str = formatter.format(curDate);return str;
 }/**
 * 格式化日期
 */public static String formatDate(String date ,String format) {
 SimpleDateFormat formatter = new SimpleDateFormat(format);
 Date curDate = null;//獲取當前時間try {
 curDate = formatter.parse(date);
 } catch (ParseException e) {
 e.printStackTrace();
 }
 String str = formatter.format(curDate);return str;
 }/**
 * 切換周的時候用
 * 獲取前/后 幾天的一個日期
 * @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 ;
 }/**
 * 獲取前/后 幾個月的一個日期 切換月的時候用
 * @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() ;
 }
}
這里有個地方需要注意一下,因為我們一個月第一天是周幾不確定,顯示GridView的時候第一天的position也不確定,但是我們可以根據前面少了幾天再添加上空對象即可:
//為了用空的值填補第一個之前的日期//先獲取在本周內是周幾int weekNum = result.get(0).weekNum -1 ;for (int j = 0 ;j DateEntity entity = new DateEntity();
 result.add(0,entity);
}
還有一個獲取陰歷日期的工具類,比較復雜,所以直接從網上找了一個,這里就不貼了。
剩下的就是去寫布局、自定義PopupWindow了,這些應該是沒什么難度吧。關于GridView選中,原理就是在Adapter里面設置一個選中方法:
private int selectedPosition = -1;// 選中的位置public void setSelectedPosition(int position) {
 selectedPosition = position;
 notifyDataSetChanged();
}
...
在Adapter的getView(int position, View convertView, ViewGroup parent) 
方法去判斷 position是否和selectedPosition 是否相等,相等就表示選中了,可以修改背景、字體顏色等等
...
當然在用到Adapter的地方也要調用setSelectedPosition方法
具體怎么使用可以參考里面的代碼。
關于GrdiView左右滑動的判斷(關鍵代碼片段):
private GestureDetector gestureDetector;//初始化
gestureDetector = new GestureDetector(context,onGestureListener);/**
 * 手勢監聽是否是左右滑動,這里認為滑動距離超過100就算左右滑動
 */private GestureDetector.OnGestureListener onGestureListener =new GestureDetector.SimpleOnGestureListener() {@Overridepublic 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("當前月份:"+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("當前月份:"+DataUtils.formatDate(date,"yyyy-MM"));
 Log.e("wenzihao","go left");break;
 }
}
...設置手勢給gridview
gridView.setOnTouchListener(new View.OnTouchListener() {@Overridepublic boolean onTouch(View view, MotionEvent event) {return gestureDetector.onTouchEvent(event);
 }
});
最后就是點擊PopupWindow的時候自定義回調方法把選中日期帶過去即可。
好了,其他的代碼也不貼了,關鍵點就那么點,沒啥太大難度,感覺主要還是考驗大家的基本功吧。
這么一個自定義日歷控件就寫好了,是不是很簡單感覺,希望能夠對大家有啟發和幫助,可以靈活自定義出設計產品需要的各種控件。
最后附上項目地址:
https://github.com/wenzhihao123/Android-CalendarView-master
—————END—————
? ? ?
? ?創作不易,點個“在看”
總結
以上是生活随笔為你收集整理的android gridview控件使用详解_Android开发实现自定义日历、日期选择控件的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 深圳一手房备案查询网(深圳一手房备案查询
- 下一篇: gram矩阵_Skip-gram
