android gridview控件使用详解_Android开发实现自定义日历、日期选择控件
點(diǎn)擊上方藍(lán)字關(guān)注???
來(lái)源:?wenzhihao123
https://www.jianshu.com/p/a2f102c728ce
前言
最近項(xiàng)目需要日歷效果,考慮用第三方的反而不太適合設(shè)計(jì)需求,修改復(fù)雜,與其這樣不入自己重新寫(xiě)一個(gè)干凈的控件。雖不是什么牛逼控件,但是也需要我們能按照設(shè)計(jì)自己寫(xiě)出來(lái)。在此記錄一下實(shí)現(xiàn)思路。
效果圖:
詳解
實(shí)現(xiàn)思路
- 頭部是一個(gè)自定義組合控件; 
- 顯示一周的日期部分用GridView 更加方便更新; 
- 切換月的部分是一個(gè)自定義PopupWindow; 
- GridView選中效果; 
- GridView根據(jù)手勢(shì)GestureDetector監(jiān)聽(tīng)左右滑動(dòng); 
- 核心其實(shí)還是Calendar類(lèi),根據(jù)這個(gè)類(lèi)我們可以獲取制定日期一周的日期集合、可以獲取制定日期一月的日期集合等等; 
- 根據(jù)陽(yáng)歷日期獲取陰歷日期 
使用:
// xml布局引用 android:id="@+id/week"
 android:layout_width="match_parent"
 android:background="@color/color_ffffff"
 android:layout_height="wrap_content">// 代碼中,自定義回調(diào)監(jiān)聽(tīng)選中的日期
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"+"時(shí)間戳:"+ date.million+"\n");
 Log.e("wenzhiao--------------",date.toString());
 }
 });//需要傳遞此種格式的日期,不傳默認(rèn)是獲取今日的日期
dataView.getData("2017-04-19");
實(shí)現(xiàn)整體邏輯
回調(diào)的日期信息封裝成一個(gè)實(shí)體類(lèi)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 ; //陰歷@Overridepublic String toString() {return "DateEntity{" +"million=" + million +", weekName='" + weekName + '\'' +", weekNum=" + weekNum +", date='" + date + '\'' +", isToday=" + isToday +", day='" + day + '\'' +", luna='" + luna + '\'' +'}';
 }
}
封裝的日期獲取的工具類(lèi):
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 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 ;
 }/**
 * 獲取當(dāng)前日期一月的日期
 * @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);
 }//為了用空的值填補(bǔ)第一個(gè)之前的日期//先獲取在本周內(nèi)是周幾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 ;
 }/**
 * 根據(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 dateFormater = new ThreadLocal() {
 @Overrideprotected 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();//過(guò)去七天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ù)前面少了幾天再添加上空對(duì)象即可:
//為了用空的值填補(bǔ)第一個(gè)之前的日期//先獲取在本周內(nèi)是周幾int weekNum = result.get(0).weekNum -1 ;for (int j = 0 ;j DateEntity entity = new DateEntity();
 result.add(0,entity);
}
還有一個(gè)獲取陰歷日期的工具類(lèi),比較復(fù)雜,所以直接從網(wǎng)上找了一個(gè),這里就不貼了。
剩下的就是去寫(xiě)布局、自定義PopupWindow了,這些應(yīng)該是沒(méi)什么難度吧。關(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);/**
 * 手勢(shì)監(jiān)聽(tīng)是否是左右滑動(dòng),這里認(rèn)為滑動(dòng)距離超過(guò)100就算左右滑動(dòng)
 */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("當(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è)置手勢(shì)給gridview
gridView.setOnTouchListener(new View.OnTouchListener() {@Overridepublic boolean onTouch(View view, MotionEvent event) {return gestureDetector.onTouchEvent(event);
 }
});
最后就是點(diǎn)擊PopupWindow的時(shí)候自定義回調(diào)方法把選中日期帶過(guò)去即可。
好了,其他的代碼也不貼了,關(guān)鍵點(diǎn)就那么點(diǎn),沒(méi)啥太大難度,感覺(jué)主要還是考驗(yàn)大家的基本功吧。
這么一個(gè)自定義日歷控件就寫(xiě)好了,是不是很簡(jiǎn)單感覺(jué),希望能夠?qū)Υ蠹矣袉l(fā)和幫助,可以靈活自定義出設(shè)計(jì)產(chǎn)品需要的各種控件。
最后附上項(xiàng)目地址:
https://github.com/wenzhihao123/Android-CalendarView-master
—————END—————
? ? ?
? ?創(chuàng)作不易,點(diǎn)個(gè)“在看”
總結(jié)
以上是生活随笔為你收集整理的android gridview控件使用详解_Android开发实现自定义日历、日期选择控件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
 
                            
                        - 上一篇: 深圳一手房备案查询网(深圳一手房备案查询
- 下一篇: gram矩阵_Skip-gram
