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

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

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

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,对应日历控件如下面图片的部分。

<?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 自定义日期段选择控件,开始时间-结束时间。内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

Android 自定义日期段选择控件功能(开始时间-结束时间)的更多相关文章

  1. html5 canvas合成海报所遇问题及解决方案总结

    这篇文章主要介绍了html5 canvas合成海报所遇问题及解决方案总结,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Html5 video标签视频的最佳实践

    这篇文章主要介绍了Html5 video标签视频的最佳实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  3. HTML5在微信内置浏览器下右上角菜单的调整字体导致页面显示错乱的问题

    HTML5在微信内置浏览器下,在右上角菜单的调整字体导致页面显示错乱的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

  4. ios – containerURLForSecurityApplicationGroupIdentifier:在iPhone和Watch模拟器上给出不同的结果

    我使用默认的XCode模板创建了一个WatchKit应用程序.我向iOSTarget,WatchkitAppTarget和WatchkitAppExtensionTarget添加了应用程序组权利.(这是应用程序组名称:group.com.lombax.fiveminutes)然后,我尝试使用iOSApp和WatchKitExtension访问共享文件夹URL:延期:iOS应用:但是,测试NSURL

  5. Ionic – Splash Screen适用于iOS,但不适用于Android

    我有一个离子应用程序,其中使用CLI命令离子资源生成的启动画面和图标iOS版本与正在渲染的启动画面完美配合,但在Android版本中,只有在加载应用程序时才会显示白屏.我检查了config.xml文件,所有路径看起来都是正确的,生成的图像出现在相应的文件夹中.(我使用了splash.psd模板来生成它们.我错过了什么?这是config.xml文件供参考,我觉得我在这里做错了–解决方法在config.xml中添加以下键:它对我有用!

  6. ios – 无法启动iPhone模拟器

    /Library/Developer/CoreSimulator/Devices/530A44CB-5978-4926-9E91-E9DBD5BFB105/data/Containers/Bundle/Application/07612A5C-659D-4C04-ACD3-D211D2830E17/ProductName.app/ProductName然后,如果您在Xcode构建设置中选择标准体系结构并再次构建和运行,则会产生以下结果:dyld:lazysymbolbindingFailed:Symbol

  7. Xamarin iOS图像在Grid内部重叠

    heyo,所以在Xamarin我有一个使用并在其中包含一对,所有这些都包含在内.这在Xamarin.Android中看起来完全没问题,但是在Xamarin.iOS中,图像与标签重叠.我不确定它的区别是什么–为什么它在Xamarin.Android中看起来不错但在iOS中它的全部都不稳定?

  8. 在iOS上向后播放HTML5视频

    我试图在iPad上反向播放HTML5视频.HTML5元素包括一个名为playbackRate的属性,它允许以更快或更慢的速率或相反的方式播放视频.根据Apple’sdocumentation,iOS不支持此属性.通过每秒多次设置currentTime属性,可以反复播放,而无需使用playbackRate.这种方法适用于桌面Safari,但似乎在iOS设备上的搜索限制为每秒1次更新–在我的情况下太慢了.有没有办法在iOS设备上向后播放HTML5视频?解决方法iOS6Safari现在支持playbackRat

  9. 使用 Swift 语言编写 Android 应用入门

    Swift标准库可以编译安卓armv7的内核,这使得可以在安卓移动设备上执行Swift语句代码。做梦,虽然Swift编译器可以胜任在安卓设备上编译Swift代码并运行。这需要的不仅仅是用Swift标准库编写一个APP,更多的是你需要一些框架来搭建你的应用用户界面,以上这些Swift标准库不能提供。简单来说,构建在安卓设备上使用的Swiftstdlib需要libiconv和libicu。通过命令行执行以下命令:gitclonegit@github.com:SwiftAndroid/libiconv-libi

  10. Android – 调用GONE然后VISIBLE使视图显示在错误的位置

    我有两个视图,A和B,视图A在视图B上方.当我以编程方式将视图A设置为GONE时,它将消失,并且它正下方的视图将转到视图A的位置.但是,当我再次将相同的视图设置为VISIBLE时,它会在视图B上显示.我不希望这样.我希望视图B回到原来的位置,这是我认为会发生的事情.我怎样才能做到这一点?编辑–代码}这里是XML:解决方法您可以尝试将两个视图放在RelativeLayout中并相对于彼此设置它们的位置.

随机推荐

  1. Flutter 网络请求框架封装详解

    这篇文章主要介绍了Flutter 网络请求框架封装详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Android单选按钮RadioButton的使用详解

    今天小编就为大家分享一篇关于Android单选按钮RadioButton的使用详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

  3. 解决android studio 打包发现generate signed apk 消失不见问题

    这篇文章主要介绍了解决android studio 打包发现generate signed apk 消失不见问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

  4. Android 实现自定义圆形listview功能的实例代码

    这篇文章主要介绍了Android 实现自定义圆形listview功能的实例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. 详解Android studio 动态fragment的用法

    这篇文章主要介绍了Android studio 动态fragment的用法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  6. Android用RecyclerView实现图标拖拽排序以及增删管理

    这篇文章主要介绍了Android用RecyclerView实现图标拖拽排序以及增删管理的方法,帮助大家更好的理解和学习使用Android,感兴趣的朋友可以了解下

  7. Android notifyDataSetChanged() 动态更新ListView案例详解

    这篇文章主要介绍了Android notifyDataSetChanged() 动态更新ListView案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

  8. Android自定义View实现弹幕效果

    这篇文章主要为大家详细介绍了Android自定义View实现弹幕效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  9. Android自定义View实现跟随手指移动

    这篇文章主要为大家详细介绍了Android自定义View实现跟随手指移动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. Android实现多点触摸操作

    这篇文章主要介绍了Android实现多点触摸操作,实现图片的放大、缩小和旋转等处理,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部