欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 自定义日期段选择控件功能(开始时间-结束时间)

程序员文章站 2022-06-09 08:20:23
开发中碰到个需求,需要在一个空间中选择完成开始和结束时间。实现的过程走的是程序员开发的老路子,找到*后自己改吧改吧就成了。当时做的时候有几个需求:1.当天为最大的结束日期,2.最大选择范围1年,3....

开发中碰到个需求,需要在一个空间中选择完成开始和结束时间。实现的过程走的是程序员开发的老路子,找到*后自己改吧改吧就成了。

当时做的时候有几个需求:1.当天为最大的结束日期,2.最大选择范围1年,3.开始时间和结束时间可以为同一天。如有其他需求实现,可以参考代码改进一下。先上效果图:

Android 自定义日期段选择控件功能(开始时间-结束时间)

视频点击后的虚影是屏幕录制的原因。实现步骤:(如有缺失什么资源,请告知。开始时间和结束时间显示自己布局内添加就可以)

1.自定义控件属性

<declare-styleable name="mycalendar">
 <attr name="dateformat" format="string"></attr>
 <attr name="titlesize" format="dimension"></attr>
 <attr name="titlecolor" format="color"></attr>
 <attr name="goicon" format="reference"></attr>
 <attr name="preicon" format="reference"></attr>
 <attr name="dayinmonthcolor" format="color"></attr>
 <attr name="dayoutmonthcolor" format="color"></attr>
 <attr name="todaycolor" format="color"></attr>
 <attr name="todayemptycirclecolor" format="color"></attr>
 <attr name="todayfillcirclecolor" format="color"></attr>
 <attr name="calendarbackground" format="color|reference"></attr>
</declare-styleable>

2.自定义控件代码

/**
 * @description: 可以选择时间范围的日历控件
 * @author mengxy
 * @emil mxy_2012_1@163.com
 * @date 2019/1/8
*/
public class calendarview extends linearlayout implements view.onclicklistener{
 private textview title;
 private recyclerview recyclerview;
 private relativelayout layout_calendar_gonext;
 private relativelayout layout_calendar_goup;
 private linearlayoutmanager linearlayoutmanager;
 private calendar curdate = calendar.getinstance();
 //从服务器获取的日期
 private date datefromserver;
 //外层主recyclerview的adapter
 private mainrvadapter mainadapter;
 private list<calendarcell> months = new arraylist<>();
 private context context;
 //相关属性
 private int titlecolor;
 private int titlesize;
 private int enableselectcolor;
 private int disableseletcolor;
 private int todaycolor;
 private int todayemptycolor;
 private int todayfillcolor;
 /** 初始日期为当前日期前一年*/
 private string time;
 private long timebefor;
 private long timenow;
 private list<string> titles = new arraylist<>();
 //点击的开始时间与结束时间
 private date sdatetime;
 private date edatetime;
 private boolean isselectingstime = true;
 private hashmap<integer, subrvadapter> alladapters = new hashmap<>();
 public calendarview(context context) {
 this(context, null);
 }
 public calendarview(context context, attributeset attrs) {
 this(context, attrs, 0);
 }
 private int maxselect = 13;
 public calendarview(context context, attributeset attrs, int defstyleattr) {
 super(context, attrs, defstyleattr);
 typedarray ta = context.obtainstyledattributes(attrs, r.styleable.mycalendar);
 titlecolor = ta.getcolor(r.styleable.mycalendar_titlecolor, color.white);
 titlesize = (int) ta.getdimension(r.styleable.mycalendar_titlesize, 15);
 enableselectcolor = ta.getcolor(r.styleable.mycalendar_dayinmonthcolor, context.getresources().getcolor(r.color.text_lable));
 disableseletcolor = ta.getcolor(r.styleable.mycalendar_dayoutmonthcolor, context.getresources().getcolor(r.color.text_unenable));
 todaycolor = ta.getcolor(r.styleable.mycalendar_todaycolor, color.blue);
 todayemptycolor = ta.getcolor(r.styleable.mycalendar_todayemptycirclecolor, color.cyan);
 todayfillcolor = ta.getcolor(r.styleable.mycalendar_todayfillcirclecolor, color.cyan);
 ta.recycle();
 this.context = context;
 init(context);
 }
 //该方法用于设置从服务器获取的时间,如果没有从服务器获取的时间将使用手机本地时间
 private void inittime() {
 calendar calendar = calendar.getinstance(); //得到日历
 calendar.settime(new date());
 calendar.add(calendar.month,-(maxselect-1));
 time = dateutils.formatdata(calendar.gettime(),constant.tformate_ymd);
 timebefor = dateutils.getdatatime(time);
 string now = dateutils.formatdata(new date(),constant.tformate_ymd);
 timenow = dateutils.getdatatime(now);
// logutils.e("之前日期:"+time+"=="+timebefor);
// logutils.e("当前日期:"+now+"=="+timenow);
 curdate = dateutil.strtocalendar(time, constant.tformate_ymd);
 datefromserver = dateutil.strtodate(time, constant.tformate_ymd);
 }
 private void init(context context) {
 bindview(context);
 rendercalendar();
 }
 private void bindview(context context) {
 view view = layoutinflater.from(context).inflate(r.layout.appoint_calendarview, this, false);
 title = (textview) view.findviewbyid(r.id.calendar_title);
 title.settextcolor(titlecolor);
 title.settextsize(titlesize);
 layout_calendar_gonext = view.findviewbyid(r.id.layout_calendar_gonext);
 layout_calendar_goup = view.findviewbyid(r.id.layout_calendar_goup);
 layout_calendar_gonext.setonclicklistener(this);
 layout_calendar_goup.setonclicklistener(this);
 recyclerview = (recyclerview) view.findviewbyid(r.id.calendar_rv);
 linearlayoutmanager = new linearlayoutmanager(this.context, linearlayoutmanager.horizontal, false);
 recyclerview.setlayoutmanager(linearlayoutmanager);
 pagersnaphelper snaphelper = new pagersnaphelper();
 snaphelper.attachtorecyclerview(recyclerview);
 addview(view);
 }
 public void rendercalendar() {
 months.clear();
 inittime();
 for (int i = 0; i < maxselect; i++) {
 arraylist<date> cells = new arraylist<>();
 if (i != 0) {
 curdate.add(calendar.month, 1);//后推一个月
 } else {
 curdate.add(calendar.month, 0);//当前月
 }
 calendar calendar = (calendar) curdate.clone();
 //将日历设置到当月第一天
 calendar.set(calendar.day_of_month, 1);
 //获得当月第一天是星期几,如果是星期一则返回1此时1-1=0证明上个月没有多余天数
 int prevdays = calendar.get(calendar.day_of_week) - 1;
 //将calendar在1号的基础上向前推prevdays天。
 calendar.add(calendar.day_of_month, -prevdays);
 //最大行数是6*7也就是,1号正好是星期六时的情况
 int maxcellcount = 6 * 7;
 while (cells.size() < maxcellcount) {
 cells.add(calendar.gettime());
 //日期后移一天
 calendar.add(calendar.day_of_month, 1);
 }
 months.add(new calendarcell(i, cells));
 }
 for (int i = 0; i < months.size(); i++) {
 //title格式 2018年6月3日
 string title = (months.get(i).getcells().get(20).getyear() + 1900) +
 "\t-\t" +
 (months.get(i).getcells().get(20).getmonth() + 1);
 titles.add(title);
 }
 title.settext(titles.get(maxselect-1));
 //只限定3个月,因此模拟给3个数值即可
 mainadapter = new mainrvadapter(r.layout.appoint_calendarview_item, months);
 recyclerview.setadapter(mainadapter);
 //recyclerview 的滚动监听
 recyclerview.addonscrolllistener(new recyclerview.onscrolllistener() {
 @override
 public void onscrollstatechanged(recyclerview recyclerview, int newstate) {
 title.settext(titles.get(linearlayoutmanager.findlastvisibleitemposition()));
 super.onscrollstatechanged(recyclerview, newstate);
 }
 });
 recyclerview.scrolltoposition(maxselect-1);
 }
 @override
 public void onclick(view v) {
 int index = linearlayoutmanager.findlastvisibleitemposition();
 logutils.e("当前项"+index);
 switch (v.getid()){
 case r.id.layout_calendar_gonext:
 if(index < maxselect-1){
 recyclerview.scrolltoposition(index+1);
 title.settext(titles.get(index+1));
 }
 break;
 case r.id.layout_calendar_goup:
 if(index > 0){
 recyclerview.scrolltoposition(index-1);
 title.settext(titles.get(index-1));
 }
 break;
 }
 }
 /**
 * 最外层水平recyclerview的adapter
 */
 private class mainrvadapter extends basequickadapter<calendarcell, baseviewholder> {
 public mainrvadapter(int layoutresid, @nullable list<calendarcell> data) {
 super(layoutresid, data);
 }
 @override
 protected void convert(baseviewholder helper, final calendarcell item) {
 if (((recyclerview) helper.getview(r.id.appoint_calendarview_item_rv)).getlayoutmanager() == null) {
 //recyclerview不能都使用同一个layoutmanager
 gridlayoutmanager manager = new gridlayoutmanager(mcontext, 7);
 //recyclerview嵌套高度不固定(wrap_content)时必须setautomeasureenabled(true),否则测量时控件高度为0
 manager.setautomeasureenabled(true);
 ((recyclerview) helper.getview(r.id.appoint_calendarview_item_rv)).setlayoutmanager(manager);
 }
 subrvadapter subrvadapter = null;
 if (alladapters.get(helper.getposition()) == null) {
 subrvadapter = new subrvadapter(r.layout.calendar_text_day, item.getcells());
 alladapters.put(helper.getposition(), subrvadapter);
 ((recyclerview) helper.getview(r.id.appoint_calendarview_item_rv)).setadapter(subrvadapter);
 } else {
 subrvadapter = alladapters.get(helper.getposition());
 ((recyclerview) helper.getview(r.id.appoint_calendarview_item_rv)).setadapter(subrvadapter);
 }
 //item 点击事件响应
 subrvadapter.setonitemclicklistener(new onitemclicklistener() {
 @override
 public void onitemclick(basequickadapter adapter, view view, int position) {
 date date = item.getcells().get(position);
 if(date.gettime() >= timebefor && date.gettime()<= timenow ){
 if (isselectingstime) {
 //正在选择开始时间
 selectsdate(item.getcells().get(position));
 } else {
 //正在选择结束时间
 selectedate(item.getcells().get(position));
 }
 }
 //更新所有的adapter,比如今天6月,需要更新6、7、8三个月份不同adapter
 iterator iterator = alladapters.entryset().iterator();
 while (iterator.hasnext()) {
 map.entry entry = (map.entry) iterator.next();
 ((subrvadapter) entry.getvalue()).notifydatasetchanged();
 }
 }
 });
 }
 }
 public void selectsdate(date date) {
 if (sdatetime != null && edatetime != null) {
 sdatetime = date;
 notifydateselectchanged();
 } else {
 sdatetime = date;
 notifydateselectchanged();
 }
 edatetime = null;
 isselectingstime = false;
 /** 当前没有选择结束时间*/
 if(this.calendasellistener != null){
 calendasellistener.selectstatus(false);
 }
 }
 public void selectedate(date date) {
 if (sdatetime != null) {
 if (date.gettime() >= sdatetime.gettime()) {
 edatetime = date;
 isselectingstime = true;
 notifydateselectchanged();
 }else {
 edatetime = sdatetime;
 sdatetime = date;
 isselectingstime = true;
 notifydateselectchanged();
 }
 /** 选择完成*/
 if(this.calendasellistener != null){
 calendasellistener.selectstatus(true);
 }
 }
 }
 /**
 * 通知开始时间跟结束时间均改变
 */
 public void notifydateselectchanged() {
 if (metimeselectlistener != null && edatetime != null) {
 metimeselectlistener.onetimeselect(edatetime);
 }
 if (mstimeselectlistener != null && sdatetime != null) {
 mstimeselectlistener.onstimeselect(sdatetime);
 }
 }
 private class subrvadapter extends basequickadapter<date, baseviewholder> {
 public subrvadapter(int layoutresid, @nullable list<date> data) {
 super(layoutresid, data);
 }
 @requiresapi(api = build.version_codes.jelly_bean)
 @override
 protected void convert(baseviewholder helper, date date) {
 helper.setisrecyclable(false);//不让recyclerview进行复用,复用会出问题
 ((calendardaytextview) helper.getview(r.id.calendar_day_tv)).setemptycolor(todayemptycolor);
 ((calendardaytextview) helper.getview(r.id.calendar_day_tv)).setfillcolor(todayfillcolor);
 int day = date.getdate();
 //设置文本
 ((calendardaytextview) helper.getview(r.id.calendar_day_tv)).settext(string.valueof(day));
 //设置颜色
 if(date.gettime() >= timebefor && date.gettime()<= timenow ){
 ((calendardaytextview) helper.getview(r.id.calendar_day_tv)).settextcolor(enableselectcolor);
 }else {
 ((calendardaytextview) helper.getview(r.id.calendar_day_tv)).settextcolor(disableseletcolor);
 }
 //更改选中文字颜色
 if(sdatetime != null && edatetime != null){
 if(date.gettime()>sdatetime.gettime() && date.gettime()<edatetime.gettime()){
 ((calendardaytextview) helper.getview(r.id.calendar_day_tv)).isselected(true);
 helper.getview(r.id.calendar_day_rl).setbackgroundcolor(getresources().getcolor(r.color.date_duration_bg));
 }
 }
 /****************************/
 if (edatetime != null && date.gettime() == edatetime.gettime()) {
 //结束时间
 if(edatetime.equals(sdatetime)){
 ((calendardayrelativelayout) helper.getview(r.id.calendar_day_rl)).issameday();
 }else {
 ((calendardayrelativelayout) helper.getview(r.id.calendar_day_rl)).isetime(true);
 }
 ((calendardaytextview) helper.getview(r.id.calendar_day_tv)).isetime(true);
 }
 if (sdatetime != null && date.gettime() == sdatetime.gettime()) {
 //开始时间
 if (edatetime != null) {
 if(edatetime.equals(sdatetime)) {
 ((calendardayrelativelayout) helper.getview(r.id.calendar_day_rl)).issameday();
 }else {
 ((calendardayrelativelayout) helper.getview(r.id.calendar_day_rl)).isstime(true);
 }
 ((calendardaytextview) helper.getview(r.id.calendar_day_tv)).isstime(true);
 } else {
 ((calendardayrelativelayout) helper.getview(r.id.calendar_day_rl)).isdurationsun(true);
 ((calendardaytextview) helper.getview(r.id.calendar_day_tv)).isstime(true);
 }
 }
 /*****************************************/
 if(date.gettime() == timenow){
 ((calendardaytextview) helper.getview(r.id.calendar_day_tv)).settoday(true);
 }
 }
 }
 private class calendarcell {
 private int position;
 arraylist<date> cells;
 public calendarcell(int position, arraylist<date> cells) {
 this.position = position;
 this.cells = cells;
 }
 public int getposition() {
 return position;
 }
 public void setposition(int position) {
 this.position = position;
 }
 public arraylist<date> getcells() {
 return cells;
 }
 public void setcells(arraylist<date> cells) {
 this.cells = cells;
 }
 }
 //开始时间的选择监听
 public interface calendarstimesellistener {
 void onstimeselect(date date);
 }
 private calendarstimesellistener mstimeselectlistener;
 public void setstimesellistener(calendarstimesellistener li) {
 mstimeselectlistener = li;
 }
 //结束时间的监听事件
 public interface calendatetimsellistener {
 void onetimeselect(date date);
 }
 private calendasellistener calendasellistener;
 /**选择日期完整性*/
 public interface calendasellistener{
 void selectstatus(boolean isok);
 }
 public void setcalendasellistener(calendasellistener calendasellistener) {
 this.calendasellistener = calendasellistener;
 }
 private calendatetimsellistener metimeselectlistener;
 public void setetimesellistener(calendatetimsellistener li) {
 metimeselectlistener = li;
 }
}

3.自定义view用到的布局 appoint_calendarview.xml,对应日历控件如下面图片的部分。

Android 自定义日期段选择控件功能(开始时间-结束时间)

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_margintop="15dp"
 android:orientation="vertical">
 
 <relativelayout
 android:layout_width="match_parent"
 android:layout_height="20dp"
 android:gravity="center_vertical"
 android:orientation="horizontal">
 <textview
 android:id="@+id/calendar_title"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerinparent="true"
 android:text="2018年"
 android:textcolor="@color/text_lable"
 android:textsize="15dp"/>
 <relativelayout
 android:id="@+id/layout_calendar_gonext"
 android:layout_width="wrap_content"
 android:layout_height="match_parent"
 android:layout_alignparentright="true"
 android:paddingleft="15dp"
 android:paddingright="15dp"
 >
 <imageview
 android:layout_width="10dp"
 android:layout_height="10dp"
 android:layout_centervertical="true"
 android:src="@mipmap/icon_arrow_right" />
 </relativelayout>
 <relativelayout
 android:id="@+id/layout_calendar_goup"
 android:layout_width="wrap_content"
 android:layout_height="match_parent"
 android:paddingleft="15dp"
 android:paddingright="15dp"
 >
 <imageview
 android:layout_width="10dp"
 android:layout_height="10dp"
 android:layout_centervertical="true"
 android:src="@mipmap/icon_back_black" />
 </relativelayout>
 
 </relativelayout>
 
 <linearlayout
 android:id="@+id/calendar_week_header"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margintop="15dp"
 android:gravity="center_vertical"
 android:orientation="horizontal"
 >
 <textview
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_gravity="center_vertical"
 android:layout_weight="1"
 android:text="@string/sun"
 android:textalignment="center"
 android:textcolor="#555"
 android:textsize="13dp" />
 
 <textview
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_gravity="center_vertical"
 android:layout_weight="1"
 android:text="@string/mon"
 android:textalignment="center"
 android:textcolor="#555"
 android:textsize="13dp" />
 
 <textview
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_gravity="center_vertical"
 android:layout_weight="1"
 android:text="@string/tue"
 android:textalignment="center"
 android:textcolor="#555"
 android:textsize="13dp" />
 
 <textview
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_gravity="center_vertical"
 android:layout_weight="1"
 android:text="@string/wed"
 android:textalignment="center"
 android:textcolor="#555"
 android:textsize="13dp" />
 
 <textview
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_gravity="center_vertical"
 android:layout_weight="1"
 android:text="@string/thu"
 android:textalignment="center"
 android:textcolor="#555"
 android:textsize="13dp" />
 
 <textview
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_gravity="center_vertical"
 android:layout_weight="1"
 android:text="@string/fri"
 android:textalignment="center"
 android:textcolor="#555"
 android:textsize="13dp" />
 
 <textview
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_gravity="center_vertical"
 android:layout_weight="1"
 android:text="@string/sat"
 android:textalignment="center"
 android:textcolor="#555"
 android:textsize="13dp" />
 </linearlayout>
 
 <android.support.v7.widget.recyclerview
 android:id="@+id/calendar_rv"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margintop="10dp"
 android:overscrollmode="never"
 />
</linearlayout>

定义控件选择后的背景部分:calendardayrelativelayout.java

import android.content.context;
import android.graphics.color;
import android.os.build;
import android.support.annotation.requiresapi;
import android.util.attributeset;
import android.widget.relativelayout;
 
 
public class calendardayrelativelayout extends relativelayout {
 public calendardayrelativelayout(context context) {
 this(context, null);
 }
 
 public calendardayrelativelayout(context context, attributeset attrs) {
 super(context, attrs);
 }
 
 @requiresapi(api = build.version_codes.jelly_bean)
 public void isdurationsat(boolean issaturday) {
 this.setbackground(getresources().getdrawable(r.drawable.appoint_calendar_sat_bg));
 }
 
 @requiresapi(api = build.version_codes.jelly_bean)
 public void isdurationsun(boolean issunday) {
 this.setbackground(getresources().getdrawable(r.drawable.appoint_calendar_sun_bg));
 }
 @requiresapi(api = build.version_codes.jelly_bean)
 public void isetime(boolean etime) {
// this.setbackgroundresource(getresources().getdrawable(r.drawable.));
 
 this.setbackground(getresources().getdrawable(r.drawable.appoint_calendar_sat_bg));
 }
 @requiresapi(api = build.version_codes.jelly_bean)
 public void isstime(boolean stime) {
// this.setbackground(getresources().getdrawable(r.mipmap.appoint_calendar_start_bg));
 this.setbackground(getresources().getdrawable(r.drawable.appoint_calendar_sun_bg));
 }
 
 /**
 * 同一天
 * */
 @requiresapi(api = build.version_codes.jelly_bean)
 public void issameday(){
 this.setbackground(getresources().getdrawable(r.drawable.appoint_calendar_same_bg));
 }
}

自定义控件内日期的calendardaytextview.java

import android.content.context;
import android.graphics.canvas;
import android.graphics.color;
import android.graphics.paint;
import android.graphics.typeface;
import android.util.attributeset;
 
/**
 * @description: 日历内日期
 * @author mengxy
 * @date 2019/1/8
*/
public class calendardaytextview extends android.support.v7.widget.appcompattextview {
 public boolean istoday;
 private boolean isstime;
 private boolean isetime;
 private context context;
 public void setemptycolor(int emptycolor) {
 this.emptycolor = emptycolor;
 }
 public void setfillcolor(int fillcolor) {
 this.fillcolor = fillcolor;
 }
 private int emptycolor = color.parsecolor("#00ff00");
 private int fillcolor = color.parsecolor("#00ff00");
 private paint mpaintstime;
 private paint mpaintetime;
 
 public calendardaytextview(context context) {
 super(context);
 initview(context);
 }
 public calendardaytextview(context context, attributeset attrs) {
 super(context, attrs);
 initview(context);
 }
 private void initview(context context) {
 this.context=context;
// mpaintstime = new paint(paint.anti_alias_flag);
// mpaintstime.setstyle(paint.style.fill);
// mpaintstime.setcolor(context.getresources().getcolor(r.color.date_time_bg));
// mpaintstime.setstrokewidth(2);
//
// mpaintetime = new paint(paint.anti_alias_flag);
// mpaintetime.setstyle(paint.style.fill);
// mpaintetime.setcolor(context.getresources().getcolor(r.color.date_time_bg));
// mpaintetime.setstrokewidth(2);
 }
 @override
 protected void ondraw(canvas canvas) {
 //根据当前逻辑开始时间必须先绘制结束时间
// if (isetime) {
// canvas.save();
// //移动到当前控件的中心,以中心为圆点绘制实心圆
// canvas.translate(getwidth() / 2, getheight() / 2);
// canvas.drawcircle(0, 0, getwidth() / 2 , mpaintetime);
// canvas.restore();
// //此处必须将圆移动回开始位置,否则文本显示会受到影响
// canvas.translate(0, 0);
// }
//
// if (isstime) {
// canvas.save();
// //移动到当前控件的中心,以中心为圆点绘制实心圆
// canvas.translate(getwidth() / 2, getheight() / 2);
// canvas.drawcircle(0, 0, getwidth() / 2 , mpaintstime);
// canvas.restore();
// //此处必须将圆移动回开始位置,否则文本显示会受到影响
// canvas.translate(0, 0);
// }
 super.ondraw(canvas);
 }
 public void settoday(boolean today) {
 istoday = today;
 this.settextcolor(context.getresources().getcolor(r.color.text_main_tab_select));
 }
 public void isetime(boolean etime) {
 isetime = etime;
// this.settextcolor(context.getresources().getcolor(r.color.date_time_tv));
// this.settypeface(typeface.defaultfromstyle(typeface.bold));
 isselected(true);
 }
 public void isstime(boolean stime) {
 isstime = stime;
 isselected(true);
// this.settextcolor(context.getresources().getcolor(r.color.date_time_tv));
// this.settypeface(typeface.defaultfromstyle(typeface.bold));
 }
 
 public void isselected(boolean isselcted){
 if(isselcted){
 this.settextcolor(context.getresources().getcolor(r.color.date_time_tv));
 this.settypeface(typeface.defaultfromstyle(typeface.bold));
 }else {
 this.settextcolor(context.getresources().getcolor(r.color.text_lable));
 }
 }
}

appoint_calendarview.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.recyclerview
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/appoint_calendarview_item_rv"
 android:layout_width="match_parent"
 android:layout_height="wrap_content">
 
</android.support.v7.widget.recyclerview>

calendar_text_day.xml

<?xml version="1.0" encoding="utf-8"?>
<com.包名.calendardayrelativelayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="44dp"
 android:gravity="center"
 android:id="@+id/calendar_day_rl"
 android:layout_margintop="5dp"
 android:layout_marginbottom="5dp"
 >
 <com..包名.calendardaytextview
 android:id="@+id/calendar_day_tv"
 android:layout_width="44dp"
 android:layout_height="44dp"
 android:layout_centerinparent="true"
 android:gravity="center"
 android:textcolor="@color/white"
 android:text="31"
 android:includefontpadding="false"
 android:textsize="13dp"/>
</com..包名.calendardayrelativelayout>

dateutil.java

import java.sql.timestamp;
import java.text.parseexception;
import java.text.simpledateformat;
import java.util.calendar;
import java.util.date;
 
public class dateutil {
 //calendar 转化 string
 public static string calendartostr(calendar calendar,string format) {
// calendar calendat = calendar.getinstance();
 simpledateformat sdf = new simpledateformat(format);
 return sdf.format(calendar.gettime());
 }
 
 //string 转化calendar
 public static calendar strtocalendar(string str,string format) {
// string str = "2012-5-27";
 simpledateformat sdf = new simpledateformat(format);
 date date = null;
 calendar calendar = null;
 try {
 date = sdf.parse(str);
 calendar = calendar.getinstance();
 calendar.settime(date);
 } catch (parseexception e) {
 e.printstacktrace();
 }
 return calendar;
 }
 
 // date 转化string
 public static string datetostr(date date,string format) {
 simpledateformat sdf = new simpledateformat(format);
// string datestr = sdf.format(new date());
 string datestr = sdf.format(date);
 return datestr;
 }
 
 // string 转化date
 public static date strtodate(string str,string format) {
 simpledateformat sdf = new simpledateformat(format);
 date date = null;
 try {
 date = sdf.parse(str);
 } catch (parseexception e) {
 e.printstacktrace();
 }
 return date;
 }
 
 //date 转化calendar
 public static calendar datetocalendar(date date) {
 calendar calendar = calendar.getinstance();
 calendar.settime(date);
 return calendar;
 }
 
 //calendar转化date
 public static date calendartodate(calendar calendar) {
 return calendar.gettime();
 }
 
 // string 转成 timestamp
 public static timestamp strtotimestamp(string str) {
// timestamp ts = timestamp.valueof("2012-1-14 08:11:00");
 return timestamp.valueof(str);
 }
 
 //date 转 timestamp
 public static timestamp datetotimestamp(date date,string format) {
 simpledateformat df = new simpledateformat(format);
 string time = df.format(new date());
 timestamp ts = timestamp.valueof(time);
 return ts;
 }
}

4.资源文件 /drawableappoint_calendar_sat_bg.xml //开始时间

<shape xmlns:android="http://schemas.android.com/apk/res/android">
 <corners android:toprightradius="44dp" android:bottomrightradius="44dp"/>
 <size android:height="44dp"/>
 <solid android:color="#41d2c4"/>
</shape>

appoint_calendar_sun_bg.xml //结束时间

<shape xmlns:android="http://schemas.android.com/apk/res/android">
 <corners
 android:bottomleftradius="44dp"
 android:topleftradius="44dp" />
 <size android:height="44dp" />
 <solid android:color="#41d2c4" />
</shape>

appoint_calendar_same_bg.xml //开始时间和结束时间是同一天

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
 <solid android:color="@color/date_duration_bg" />
 <corners android:radius="60dp" />
</shape>

/value 

<string name="sun">日</string>
<string name="mon">一</string>
<string name="tue">二</string>
<string name="wed">三</string>
<string name="thu">四</string>
<string name="fri">五</string>
<string name="sat">六</string>
 
<color name="date_duration_bg">#41d2c4</color>

5.在activity中使用 activity_selectdate.xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:background="@color/white"
 android:orientation="vertical">
 
 <relativelayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margintop="40dp">
 
 <framelayout
 android:id="@+id/layout_line"
 android:layout_width="10dp"
 android:layout_height="1dp"
 android:layout_centerinparent="true"
 android:background="#35c1b5" />
 <textview
 android:id="@+id/tv_startime"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_toleftof="@+id/layout_line"
 android:layout_marginright="22.5dp"
 android:textcolor="#35c1b5"
 android:textsize="14dp"
 android:text="@string/startime"
 />
 <textview
 android:id="@+id/tv_endtime"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_torightof="@+id/layout_line"
 android:layout_marginleft="22.5dp"
 android:textcolor="#35c1b5"
 android:textsize="14dp"
 android:text="@string/endtime"
 />
 </relativelayout>
 <framelayout
 android:layout_width="match_parent"
 android:layout_height="0.5dp"
 android:layout_margintop="10dp"
 android:background="@color/bg_line"
 />
 <com.包名.calendarview
 android:id="@+id/calendarview"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 app:titlecolor = "@color/text_lable"
 />
</linearlayout>

selecttimeactivity.java

public class selecttimeactivity extends baseactivity {
 
 @bindview(r.id.tv_title)
 textview tvtitle;
 @bindview(r.id.iv_title_back)
 imageview ivtitleback;
 @bindview(r.id.tv_title_left)
 textview tvtitleleft;
 @bindview(r.id.layout_title_left)
 relativelayout layouttitleleft;
 @bindview(r.id.tv_title_right)
 textview tvtitleright;
 @bindview(r.id.layout_title_right)
 relativelayout layouttitleright;
 @bindview(r.id.layout_line)
 framelayout layoutline;
 @bindview(r.id.tv_startime)
 textview tvstartime;
 @bindview(r.id.tv_endtime)
 textview tvendtime;
 @bindview(r.id.calendarview)
 calendarview calendarview;
 private string startime;
 private string endtime;
 private boolean isselecgok = false;
 @override
 protected void oncreate(@nullable bundle savedinstancestate) {
 super.oncreate(savedinstancestate);
 setcontentview(r.layout.activity_selectdate);
 butterknife.bind(this);
 setstatusbar(true);
 initview();
 }
 
 private void initview() {
 tvtitle.settext(getstring(r.string.selecttime));
 ivtitleback.setvisibility(view.gone);
 tvtitleleft.settext(getstring(r.string.cancel));
 tvtitleright.settext(getstring(r.string.confirm));
 calendarview.setetimesellistener(new calendarview.calendatetimsellistener() {
 @override
 public void onetimeselect(date date) {
 if (date != null) {
 endtime = dateutils.formatdata(date, constant.tformate_ymd);
 tvendtime.settext(endtime);
 }else {
 endtime = null;
 }
 }
 });
 calendarview.setstimesellistener(new calendarview.calendarstimesellistener() {
 @override
 public void onstimeselect(date date) {
 if (date != null) {
 startime = dateutils.formatdata(date, constant.tformate_ymd);
 tvstartime.settext(startime);
 }else {
 startime = null;
 }
 }
 });
 calendarview.setcalendasellistener(new calendarview.calendasellistener() {
 @override
 public void selectstatus(boolean isok) {
 isselecgok = isok;
 }
 });
 }
 
 @onclick({r.id.tv_title_left, r.id.tv_title_right})
 public void onclick(view view) {
 switch (view.getid()) {
 case r.id.tv_title_left:
 finish();
 break;
 case r.id.tv_title_right:
 if(textutils.isempty(startime)){
 toastutils.showtoast(getstring(r.string.history_alert1));
 return;
 }
 if(textutils.isempty(endtime) || !isselecgok){
 toastutils.showtoast(getresources().getstring(r.string.history_alert));
 return;
 }
 intent intent = new intent();
 intent.putextra("startime",startime);
 intent.putextra("endtime",endtime);
 setresult(result_ok,intent);
 finish();
 break;
 }
 }
}

recycleradapter引用

implementation 'com.github.cymchad:baserecyclerviewadapterhelper:2.9.30'

到此这篇关于android 自定义日期段选择控件,开始时间-结束时间。的文章就介绍到这了,更多相关android 自定义日期段选择控件,开始时间-结束时间。内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!