当前位置:   article > 正文

如何实现Android自定义日期段选择控件功能_手机开发 日期选择控件

手机开发 日期选择控件

原文出处

标题:如何实现Android自定义日期段选择控件功能

作者:小猪

原文链接:如何实现Android自定义日期段选择控件功能 - 移动开发 - 亿速云

前言

这篇文章主要讲解了如何实现Android自定义日期段选择控件功能,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

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

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

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

1.自定义控件属性

  1. <declare-styleable name="MyCalendar">
  2. <attr name="dateformat" format="string"></attr>
  3. <attr name="titleSize" format="dimension"></attr>
  4. <attr name="titleColor" format="color"></attr>
  5. <attr name="goIcon" format="reference"></attr>
  6. <attr name="preIcon" format="reference"></attr>
  7. <attr name="dayInMonthColor" format="color"></attr>
  8. <attr name="dayOutMonthcolor" format="color"></attr>
  9. <attr name="todayColor" format="color"></attr>
  10. <attr name="todayEmptycircleColor" format="color"></attr>
  11. <attr name="todayFillcircleColor" format="color"></attr>
  12. <attr name="calendarbackground" format="color|reference"></attr>
  13. </declare-styleable>

2.自定义控件代码

  1. /**
  2. * @Description: 可以选择时间范围的日历控件
  3. * @Author MengXY
  4. * @Emil mxy_2012_1@163.com
  5. * @Date 2019/1/8
  6. */
  7. public class CalendarView extends LinearLayout implements View.OnClickListener{
  8. private TextView title;
  9. private RecyclerView recyclerView;
  10. private RelativeLayout layout_calendar_gonext;
  11. private RelativeLayout layout_calendar_goup;
  12. private LinearLayoutManager linearLayoutManager;
  13. private Calendar curDate = Calendar.getInstance();
  14. //从服务器获取的日期
  15. private Date dateFromServer;
  16. //外层主recyclerview的adapter
  17. private MainRvAdapter mainAdapter;
  18. private List<CalendarCell> months = new ArrayList<>();
  19. private Context context;
  20. //相关属性
  21. private int titleColor;
  22. private int titleSize;
  23. private int enableSelectColor;
  24. private int disableSeletColor;
  25. private int todayColor;
  26. private int todayEmptyColor;
  27. private int todayFillColor;
  28. /** 初始日期为当前日期前一年*/
  29. private String time;
  30. private long timeBefor;
  31. private long timeNow;
  32. private List<String> titles = new ArrayList<>();
  33. //点击的开始时间与结束时间
  34. private Date sDateTime;
  35. private Date eDateTime;
  36. private boolean isSelectingSTime = true;
  37. private HashMap<Integer, SubRvAdapter> allAdapters = new HashMap<>();
  38. public CalendarView(Context context) {
  39. this(context, null);
  40. }
  41. public CalendarView(Context context, AttributeSet attrs) {
  42. this(context, attrs, 0);
  43. }
  44. private int maxSelect = 13;
  45. public CalendarView(Context context, AttributeSet attrs, int defStyleAttr) {
  46. super(context, attrs, defStyleAttr);
  47. TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCalendar);
  48. titleColor = ta.getColor(R.styleable.MyCalendar_titleColor, Color.WHITE);
  49. titleSize = (int) ta.getDimension(R.styleable.MyCalendar_titleSize, 15);
  50. enableSelectColor = ta.getColor(R.styleable.MyCalendar_dayInMonthColor, context.getResources().getColor(R.color.text_lable));
  51. disableSeletColor = ta.getColor(R.styleable.MyCalendar_dayOutMonthcolor, context.getResources().getColor(R.color.text_unenable));
  52. todayColor = ta.getColor(R.styleable.MyCalendar_todayColor, Color.BLUE);
  53. todayEmptyColor = ta.getColor(R.styleable.MyCalendar_todayEmptycircleColor, Color.CYAN);
  54. todayFillColor = ta.getColor(R.styleable.MyCalendar_todayFillcircleColor, Color.CYAN);
  55. ta.recycle();
  56. this.context = context;
  57. init(context);
  58. }
  59. //该方法用于设置从服务器获取的时间,如果没有从服务器获取的时间将使用手机本地时间
  60. private void initTime() {
  61. Calendar calendar = Calendar.getInstance(); //得到日历
  62. calendar.setTime(new Date());
  63. calendar.add(Calendar.MONTH,-(maxSelect-1));
  64. time = DateUtils.formatData(calendar.getTime(),Constant.TFORMATE_YMD);
  65. timeBefor = DateUtils.getDataTime(time);
  66. String now = DateUtils.formatData(new Date(),Constant.TFORMATE_YMD);
  67. timeNow = DateUtils.getDataTime(now);
  68. // LogUtils.e("之前日期:"+time+"=="+timeBefor);
  69. // LogUtils.e("当前日期:"+now+"=="+timeNow);
  70. curDate = DateUtil.strToCalendar(time, Constant.TFORMATE_YMD);
  71. dateFromServer = DateUtil.strToDate(time, Constant.TFORMATE_YMD);
  72. }
  73. private void init(Context context) {
  74. bindView(context);
  75. renderCalendar();
  76. }
  77. private void bindView(Context context) {
  78. View view = LayoutInflater.from(context).inflate(R.layout.appoint_calendarview, this, false);
  79. title = (TextView) view.findViewById(R.id.calendar_title);
  80. title.setTextColor(titleColor);
  81. title.setTextSize(titleSize);
  82. layout_calendar_gonext = view.findViewById(R.id.layout_calendar_gonext);
  83. layout_calendar_goup = view.findViewById(R.id.layout_calendar_goup);
  84. layout_calendar_gonext.setOnClickListener(this);
  85. layout_calendar_goup.setOnClickListener(this);
  86. recyclerView = (RecyclerView) view.findViewById(R.id.calendar_rv);
  87. linearLayoutManager = new LinearLayoutManager(this.context, LinearLayoutManager.HORIZONTAL, false);
  88. recyclerView.setLayoutManager(linearLayoutManager);
  89. PagerSnapHelper snapHelper = new PagerSnapHelper();
  90. snapHelper.attachToRecyclerView(recyclerView);
  91. addView(view);
  92. }
  93. public void renderCalendar() {
  94. months.clear();
  95. initTime();
  96. for (int i = 0; i < maxSelect; i++) {
  97. ArrayList<Date> cells = new ArrayList<>();
  98. if (i != 0) {
  99. curDate.add(Calendar.MONTH, 1);//后推一个月
  100. } else {
  101. curDate.add(Calendar.MONTH, 0);//当前月
  102. }
  103. Calendar calendar = (Calendar) curDate.clone();
  104. //将日历设置到当月第一天
  105. calendar.set(Calendar.DAY_OF_MONTH, 1);
  106. //获得当月第一天是星期几,如果是星期一则返回1此时1-1=0证明上个月没有多余天数
  107. int prevDays = calendar.get(Calendar.DAY_OF_WEEK) - 1;
  108. //将calendar在1号的基础上向前推prevdays天。
  109. calendar.add(Calendar.DAY_OF_MONTH, -prevDays);
  110. //最大行数是6*7也就是,1号正好是星期六时的情况
  111. int maxCellcount = 6 * 7;
  112. while (cells.size() < maxCellcount) {
  113. cells.add(calendar.getTime());
  114. //日期后移一天
  115. calendar.add(calendar.DAY_OF_MONTH, 1);
  116. }
  117. months.add(new CalendarCell(i, cells));
  118. }
  119. for (int i = 0; i < months.size(); i++) {
  120. //title格式 201863
  121. String title = (months.get(i).getCells().get(20).getYear() + 1900) +
  122. "\t-\t" +
  123. (months.get(i).getCells().get(20).getMonth() + 1);
  124. titles.add(title);
  125. }
  126. title.setText(titles.get(maxSelect-1));
  127. //只限定3个月,因此模拟给3个数值即可
  128. mainAdapter = new MainRvAdapter(R.layout.appoint_calendarview_item, months);
  129. recyclerView.setAdapter(mainAdapter);
  130. //recyclerview 的滚动监听
  131. recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
  132. @Override
  133. public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
  134. title.setText(titles.get(linearLayoutManager.findLastVisibleItemPosition()));
  135. super.onScrollStateChanged(recyclerView, newState);
  136. }
  137. });
  138. recyclerView.scrollToPosition(maxSelect-1);
  139. }
  140. @Override
  141. public void onClick(View v) {
  142. int index = linearLayoutManager.findLastVisibleItemPosition();
  143. LogUtils.e("当前项"+index);
  144. switch (v.getId()){
  145. case R.id.layout_calendar_gonext:
  146. if(index < maxSelect-1){
  147. recyclerView.scrollToPosition(index+1);
  148. title.setText(titles.get(index+1));
  149. }
  150. break;
  151. case R.id.layout_calendar_goup:
  152. if(index > 0){
  153. recyclerView.scrollToPosition(index-1);
  154. title.setText(titles.get(index-1));
  155. }
  156. break;
  157. }
  158. }
  159. /**
  160. * 最外层水平recyclerview的adapter
  161. */
  162. private class MainRvAdapter extends BaseQuickAdapter<CalendarCell, BaseViewHolder> {
  163. public MainRvAdapter(int layoutResId, @Nullable List<CalendarCell> data) {
  164. super(layoutResId, data);
  165. }
  166. @Override
  167. protected void convert(BaseViewHolder helper, final CalendarCell item) {
  168. if (((RecyclerView) helper.getView(R.id.appoint_calendarview_item_rv)).getLayoutManager() == null) {
  169. //RecyclerView不能都使用同一个LayoutManager
  170. GridLayoutManager manager = new GridLayoutManager(mContext, 7);
  171. //recyclerview嵌套高度不固定(wrap_content)时必须setAutoMeasureEnabled(true),否则测量时控件高度为0
  172. manager.setAutoMeasureEnabled(true);
  173. ((RecyclerView) helper.getView(R.id.appoint_calendarview_item_rv)).setLayoutManager(manager);
  174. }
  175. SubRvAdapter subRvAdapter = null;
  176. if (allAdapters.get(helper.getPosition()) == null) {
  177. subRvAdapter = new SubRvAdapter(R.layout.calendar_text_day, item.getCells());
  178. allAdapters.put(helper.getPosition(), subRvAdapter);
  179. ((RecyclerView) helper.getView(R.id.appoint_calendarview_item_rv)).setAdapter(subRvAdapter);
  180. } else {
  181. subRvAdapter = allAdapters.get(helper.getPosition());
  182. ((RecyclerView) helper.getView(R.id.appoint_calendarview_item_rv)).setAdapter(subRvAdapter);
  183. }
  184. //item 点击事件响应
  185. subRvAdapter.setOnItemClickListener(new OnItemClickListener() {
  186. @Override
  187. public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
  188. Date date = item.getCells().get(position);
  189. if(date.getTime() >= timeBefor && date.getTime()<= timeNow ){
  190. if (isSelectingSTime) {
  191. //正在选择开始时间
  192. selectSDate(item.getCells().get(position));
  193. } else {
  194. //正在选择结束时间
  195. selectEDate(item.getCells().get(position));
  196. }
  197. }
  198. //更新所有的adapter,比如今天6月,需要更新678三个月份不同adapter
  199. Iterator iterator = allAdapters.entrySet().iterator();
  200. while (iterator.hasNext()) {
  201. Map.Entry entry = (Map.Entry) iterator.next();
  202. ((SubRvAdapter) entry.getValue()).notifyDataSetChanged();
  203. }
  204. }
  205. });
  206. }
  207. }
  208. public void selectSDate(Date date) {
  209. if (sDateTime != null && eDateTime != null) {
  210. sDateTime = date;
  211. notifyDateSelectChanged();
  212. } else {
  213. sDateTime = date;
  214. notifyDateSelectChanged();
  215. }
  216. eDateTime = null;
  217. isSelectingSTime = false;
  218. /** 当前没有选择结束时间*/
  219. if(this.calendaSelListener != null){
  220. calendaSelListener.selectStatus(false);
  221. }
  222. }
  223. public void selectEDate(Date date) {
  224. if (sDateTime != null) {
  225. if (date.getTime() >= sDateTime.getTime()) {
  226. eDateTime = date;
  227. isSelectingSTime = true;
  228. notifyDateSelectChanged();
  229. }else {
  230. eDateTime = sDateTime;
  231. sDateTime = date;
  232. isSelectingSTime = true;
  233. notifyDateSelectChanged();
  234. }
  235. /** 选择完成*/
  236. if(this.calendaSelListener != null){
  237. calendaSelListener.selectStatus(true);
  238. }
  239. }
  240. }
  241. /**
  242. * 通知开始时间跟结束时间均改变
  243. */
  244. public void notifyDateSelectChanged() {
  245. if (mETimeSelectListener != null && eDateTime != null) {
  246. mETimeSelectListener.onETimeSelect(eDateTime);
  247. }
  248. if (mSTimeSelectListener != null && sDateTime != null) {
  249. mSTimeSelectListener.onSTimeSelect(sDateTime);
  250. }
  251. }
  252. private class SubRvAdapter extends BaseQuickAdapter<Date, BaseViewHolder> {
  253. public SubRvAdapter(int layoutResId, @Nullable List<Date> data) {
  254. super(layoutResId, data);
  255. }
  256. @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
  257. @Override
  258. protected void convert(BaseViewHolder helper, Date date) {
  259. helper.setIsRecyclable(false);//不让recyclerview进行复用,复用会出问题
  260. ((CalendarDayTextView) helper.getView(R.id.calendar_day_tv)).setEmptyColor(todayEmptyColor);
  261. ((CalendarDayTextView) helper.getView(R.id.calendar_day_tv)).setFillColor(todayFillColor);
  262. int day = date.getDate();
  263. //设置文本
  264. ((CalendarDayTextView) helper.getView(R.id.calendar_day_tv)).setText(String.valueOf(day));
  265. //设置颜色
  266. if(date.getTime() >= timeBefor && date.getTime()<= timeNow ){
  267. ((CalendarDayTextView) helper.getView(R.id.calendar_day_tv)).setTextColor(enableSelectColor);
  268. }else {
  269. ((CalendarDayTextView) helper.getView(R.id.calendar_day_tv)).setTextColor(disableSeletColor);
  270. }
  271. //更改选中文字颜色
  272. if(sDateTime != null && eDateTime != null){
  273. if(date.getTime()>sDateTime.getTime() && date.getTime()<eDateTime.getTime()){
  274. ((CalendarDayTextView) helper.getView(R.id.calendar_day_tv)).isSelected(true);
  275. helper.getView(R.id.calendar_day_rl).setBackgroundColor(getResources().getColor(R.color.date_duration_bg));
  276. }
  277. }
  278. /****************************/
  279. if (eDateTime != null && date.getTime() == eDateTime.getTime()) {
  280. //结束时间
  281. if(eDateTime.equals(sDateTime)){
  282. ((CalendarDayRelativeLayout) helper.getView(R.id.calendar_day_rl)).isSameDay();
  283. }else {
  284. ((CalendarDayRelativeLayout) helper.getView(R.id.calendar_day_rl)).isETime(true);
  285. }
  286. ((CalendarDayTextView) helper.getView(R.id.calendar_day_tv)).isETime(true);
  287. }
  288. if (sDateTime != null && date.getTime() == sDateTime.getTime()) {
  289. //开始时间
  290. if (eDateTime != null) {
  291. if(eDateTime.equals(sDateTime)) {
  292. ((CalendarDayRelativeLayout) helper.getView(R.id.calendar_day_rl)).isSameDay();
  293. }else {
  294. ((CalendarDayRelativeLayout) helper.getView(R.id.calendar_day_rl)).isSTime(true);
  295. }
  296. ((CalendarDayTextView) helper.getView(R.id.calendar_day_tv)).isSTime(true);
  297. } else {
  298. ((CalendarDayRelativeLayout) helper.getView(R.id.calendar_day_rl)).isDurationSun(true);
  299. ((CalendarDayTextView) helper.getView(R.id.calendar_day_tv)).isSTime(true);
  300. }
  301. }
  302. /*****************************************/
  303. if(date.getTime() == timeNow){
  304. ((CalendarDayTextView) helper.getView(R.id.calendar_day_tv)).setToday(true);
  305. }
  306. }
  307. }
  308. private class CalendarCell {
  309. private int position;
  310. ArrayList<Date> cells;
  311. public CalendarCell(int position, ArrayList<Date> cells) {
  312. this.position = position;
  313. this.cells = cells;
  314. }
  315. public int getPosition() {
  316. return position;
  317. }
  318. public void setPosition(int position) {
  319. this.position = position;
  320. }
  321. public ArrayList<Date> getCells() {
  322. return cells;
  323. }
  324. public void setCells(ArrayList<Date> cells) {
  325. this.cells = cells;
  326. }
  327. }
  328. //开始时间的选择监听
  329. public interface CalendarSTimeSelListener {
  330. void onSTimeSelect(Date date);
  331. }
  332. private CalendarSTimeSelListener mSTimeSelectListener;
  333. public void setSTimeSelListener(CalendarSTimeSelListener li) {
  334. mSTimeSelectListener = li;
  335. }
  336. //结束时间的监听事件
  337. public interface CalendatEtimSelListener {
  338. void onETimeSelect(Date date);
  339. }
  340. private CalendaSelListener calendaSelListener;
  341. /**选择日期完整性*/
  342. public interface CalendaSelListener{
  343. void selectStatus(boolean isOk);
  344. }
  345. public void setCalendaSelListener(CalendaSelListener calendaSelListener) {
  346. this.calendaSelListener = calendaSelListener;
  347. }
  348. private CalendatEtimSelListener mETimeSelectListener;
  349. public void setETimeSelListener(CalendatEtimSelListener li) {
  350. mETimeSelectListener = li;
  351. }
  352. }

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

  1. <&#63;xml version="1.0" encoding="utf-8"&#63;>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:layout_marginTop="15dp"
  6. android:orientation="vertical">
  7. <RelativeLayout
  8. android:layout_width="match_parent"
  9. android:layout_height="20dp"
  10. android:gravity="center_vertical"
  11. android:orientation="horizontal">
  12. <TextView
  13. android:id="@+id/calendar_title"
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:layout_centerInParent="true"
  17. android:text="2018年"
  18. android:textColor="@color/text_lable"
  19. android:textSize="15dp"/>
  20. <RelativeLayout
  21. android:id="@+id/layout_calendar_gonext"
  22. android:layout_width="wrap_content"
  23. android:layout_height="match_parent"
  24. android:layout_alignParentRight="true"
  25. android:paddingLeft="15dp"
  26. android:paddingRight="15dp"
  27. >
  28. <ImageView
  29. android:layout_width="10dp"
  30. android:layout_height="10dp"
  31. android:layout_centerVertical="true"
  32. android:src="@mipmap/icon_arrow_right" />
  33. </RelativeLayout>
  34. <RelativeLayout
  35. android:id="@+id/layout_calendar_goup"
  36. android:layout_width="wrap_content"
  37. android:layout_height="match_parent"
  38. android:paddingLeft="15dp"
  39. android:paddingRight="15dp"
  40. >
  41. <ImageView
  42. android:layout_width="10dp"
  43. android:layout_height="10dp"
  44. android:layout_centerVertical="true"
  45. android:src="@mipmap/icon_back_black" />
  46. </RelativeLayout>
  47. </RelativeLayout>
  48. <LinearLayout
  49. android:id="@+id/calendar_week_header"
  50. android:layout_width="match_parent"
  51. android:layout_height="wrap_content"
  52. android:layout_marginTop="15dp"
  53. android:gravity="center_vertical"
  54. android:orientation="horizontal"
  55. >
  56. <TextView
  57. android:layout_width="0dp"
  58. android:layout_height="wrap_content"
  59. android:layout_gravity="center_vertical"
  60. android:layout_weight="1"
  61. android:text="@string/sun"
  62. android:textAlignment="center"
  63. android:textColor="#555"
  64. android:textSize="13dp" />
  65. <TextView
  66. android:layout_width="0dp"
  67. android:layout_height="wrap_content"
  68. android:layout_gravity="center_vertical"
  69. android:layout_weight="1"
  70. android:text="@string/mon"
  71. android:textAlignment="center"
  72. android:textColor="#555"
  73. android:textSize="13dp" />
  74. <TextView
  75. android:layout_width="0dp"
  76. android:layout_height="wrap_content"
  77. android:layout_gravity="center_vertical"
  78. android:layout_weight="1"
  79. android:text="@string/tue"
  80. android:textAlignment="center"
  81. android:textColor="#555"
  82. android:textSize="13dp" />
  83. <TextView
  84. android:layout_width="0dp"
  85. android:layout_height="wrap_content"
  86. android:layout_gravity="center_vertical"
  87. android:layout_weight="1"
  88. android:text="@string/wed"
  89. android:textAlignment="center"
  90. android:textColor="#555"
  91. android:textSize="13dp" />
  92. <TextView
  93. android:layout_width="0dp"
  94. android:layout_height="wrap_content"
  95. android:layout_gravity="center_vertical"
  96. android:layout_weight="1"
  97. android:text="@string/thu"
  98. android:textAlignment="center"
  99. android:textColor="#555"
  100. android:textSize="13dp" />
  101. <TextView
  102. android:layout_width="0dp"
  103. android:layout_height="wrap_content"
  104. android:layout_gravity="center_vertical"
  105. android:layout_weight="1"
  106. android:text="@string/fri"
  107. android:textAlignment="center"
  108. android:textColor="#555"
  109. android:textSize="13dp" />
  110. <TextView
  111. android:layout_width="0dp"
  112. android:layout_height="wrap_content"
  113. android:layout_gravity="center_vertical"
  114. android:layout_weight="1"
  115. android:text="@string/sat"
  116. android:textAlignment="center"
  117. android:textColor="#555"
  118. android:textSize="13dp" />
  119. </LinearLayout>
  120. <android.support.v7.widget.RecyclerView
  121. android:id="@+id/calendar_rv"
  122. android:layout_width="match_parent"
  123. android:layout_height="wrap_content"
  124. android:layout_marginTop="10dp"
  125. android:overScrollMode="never"
  126. />
  127. </LinearLayout>

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

  1. import android.content.Context;
  2. import android.graphics.Color;
  3. import android.os.Build;
  4. import android.support.annotation.RequiresApi;
  5. import android.util.AttributeSet;
  6. import android.widget.RelativeLayout;
  7. public class CalendarDayRelativeLayout extends RelativeLayout {
  8. public CalendarDayRelativeLayout(Context context) {
  9. this(context, null);
  10. }
  11. public CalendarDayRelativeLayout(Context context, AttributeSet attrs) {
  12. super(context, attrs);
  13. }
  14. @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
  15. public void isDurationSat(boolean isSaturday) {
  16. this.setBackground(getResources().getDrawable(R.drawable.appoint_calendar_sat_bg));
  17. }
  18. @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
  19. public void isDurationSun(boolean isSunday) {
  20. this.setBackground(getResources().getDrawable(R.drawable.appoint_calendar_sun_bg));
  21. }
  22. @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
  23. public void isETime(boolean etime) {
  24. // this.setBackgroundResource(getResources().getDrawable(R.drawable.));
  25. this.setBackground(getResources().getDrawable(R.drawable.appoint_calendar_sat_bg));
  26. }
  27. @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
  28. public void isSTime(boolean stime) {
  29. // this.setBackground(getResources().getDrawable(R.mipmap.appoint_calendar_start_bg));
  30. this.setBackground(getResources().getDrawable(R.drawable.appoint_calendar_sun_bg));
  31. }
  32. /**
  33. * 同一天
  34. * */
  35. @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
  36. public void isSameDay(){
  37. this.setBackground(getResources().getDrawable(R.drawable.appoint_calendar_same_bg));
  38. }
  39. }

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

  1. import android.content.Context;
  2. import android.graphics.Canvas;
  3. import android.graphics.Color;
  4. import android.graphics.Paint;
  5. import android.graphics.Typeface;
  6. import android.util.AttributeSet;
  7. /**
  8. * @Description: 日历内日期
  9. * @Author MengXY
  10. * @Date 2019/1/8
  11. */
  12. public class CalendarDayTextView extends android.support.v7.widget.AppCompatTextView {
  13. public boolean isToday;
  14. private boolean isSTime;
  15. private boolean isETime;
  16. private Context context;
  17. public void setEmptyColor(int emptyColor) {
  18. this.emptyColor = emptyColor;
  19. }
  20. public void setFillColor(int fillColor) {
  21. this.fillColor = fillColor;
  22. }
  23. private int emptyColor = Color.parseColor("#00ff00");
  24. private int fillColor = Color.parseColor("#00ff00");
  25. private Paint mPaintSTime;
  26. private Paint mPaintETime;
  27. public CalendarDayTextView(Context context) {
  28. super(context);
  29. initview(context);
  30. }
  31. public CalendarDayTextView(Context context, AttributeSet attrs) {
  32. super(context, attrs);
  33. initview(context);
  34. }
  35. private void initview(Context context) {
  36. this.context=context;
  37. // mPaintSTime = new Paint(Paint.ANTI_ALIAS_FLAG);
  38. // mPaintSTime.setStyle(Paint.Style.FILL);
  39. // mPaintSTime.setColor(context.getResources().getColor(R.color.date_time_bg));
  40. // mPaintSTime.setStrokeWidth(2);
  41. //
  42. // mPaintETime = new Paint(Paint.ANTI_ALIAS_FLAG);
  43. // mPaintETime.setStyle(Paint.Style.FILL);
  44. // mPaintETime.setColor(context.getResources().getColor(R.color.date_time_bg));
  45. // mPaintETime.setStrokeWidth(2);
  46. }
  47. @Override
  48. protected void onDraw(Canvas canvas) {
  49. //根据当前逻辑开始时间必须先绘制结束时间
  50. // if (isETime) {
  51. // canvas.save();
  52. // //移动到当前控件的中心,以中心为圆点绘制实心圆
  53. // canvas.translate(getWidth() / 2, getHeight() / 2);
  54. // canvas.drawCircle(0, 0, getWidth() / 2 , mPaintETime);
  55. // canvas.restore();
  56. // //此处必须将圆移动回开始位置,否则文本显示会受到影响
  57. // canvas.translate(0, 0);
  58. // }
  59. //
  60. // if (isSTime) {
  61. // canvas.save();
  62. // //移动到当前控件的中心,以中心为圆点绘制实心圆
  63. // canvas.translate(getWidth() / 2, getHeight() / 2);
  64. // canvas.drawCircle(0, 0, getWidth() / 2 , mPaintSTime);
  65. // canvas.restore();
  66. // //此处必须将圆移动回开始位置,否则文本显示会受到影响
  67. // canvas.translate(0, 0);
  68. // }
  69. super.onDraw(canvas);
  70. }
  71. public void setToday(boolean today) {
  72. isToday = today;
  73. this.setTextColor(context.getResources().getColor(R.color.text_main_tab_select));
  74. }
  75. public void isETime(boolean etime) {
  76. isETime = etime;
  77. // this.setTextColor(context.getResources().getColor(R.color.date_time_tv));
  78. // this.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
  79. isSelected(true);
  80. }
  81. public void isSTime(boolean stime) {
  82. isSTime = stime;
  83. isSelected(true);
  84. // this.setTextColor(context.getResources().getColor(R.color.date_time_tv));
  85. // this.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
  86. }
  87. public void isSelected(boolean isSelcted){
  88. if(isSelcted){
  89. this.setTextColor(context.getResources().getColor(R.color.date_time_tv));
  90. this.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
  91. }else {
  92. this.setTextColor(context.getResources().getColor(R.color.text_lable));
  93. }
  94. }
  95. }

appoint_calendarview.xml

  1. <&#63;xml version="1.0" encoding="utf-8"&#63;>
  2. <android.support.v7.widget.RecyclerView
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:id="@+id/appoint_calendarview_item_rv"
  5. android:layout_width="match_parent"
  6. android:layout_height="wrap_content">
  7. </android.support.v7.widget.RecyclerView>

calendar_text_day.xml

  1. <&#63;xml version="1.0" encoding="utf-8"&#63;>
  2. <com.包名.CalendarDayRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="44dp"
  5. android:gravity="center"
  6. android:id="@+id/calendar_day_rl"
  7. android:layout_marginTop="5dp"
  8. android:layout_marginBottom="5dp"
  9. >
  10. <com..包名.CalendarDayTextView
  11. android:id="@+id/calendar_day_tv"
  12. android:layout_width="44dp"
  13. android:layout_height="44dp"
  14. android:layout_centerInParent="true"
  15. android:gravity="center"
  16. android:textColor="@color/white"
  17. android:text="31"
  18. android:includeFontPadding="false"
  19. android:textSize="13dp"/>
  20. </com..包名.CalendarDayRelativeLayout>

DateUtil.java

  1. import java.sql.Timestamp;
  2. import java.text.ParseException;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Calendar;
  5. import java.util.Date;
  6. public class DateUtil {
  7. //Calendar 转化 String
  8. public static String calendarToStr(Calendar calendar,String format) {
  9. // Calendar calendat = Calendar.getInstance();
  10. SimpleDateFormat sdf = new SimpleDateFormat(format);
  11. return sdf.format(calendar.getTime());
  12. }
  13. //String 转化Calendar
  14. public static Calendar strToCalendar(String str,String format) {
  15. // String str = "2012-5-27";
  16. SimpleDateFormat sdf = new SimpleDateFormat(format);
  17. Date date = null;
  18. Calendar calendar = null;
  19. try {
  20. date = sdf.parse(str);
  21. calendar = Calendar.getInstance();
  22. calendar.setTime(date);
  23. } catch (ParseException e) {
  24. e.printStackTrace();
  25. }
  26. return calendar;
  27. }
  28. // Date 转化String
  29. public static String dateTostr(Date date,String format) {
  30. SimpleDateFormat sdf = new SimpleDateFormat(format);
  31. // String dateStr = sdf.format(new Date());
  32. String dateStr = sdf.format(date);
  33. return dateStr;
  34. }
  35. // String 转化Date
  36. public static Date strToDate(String str,String format) {
  37. SimpleDateFormat sdf = new SimpleDateFormat(format);
  38. Date date = null;
  39. try {
  40. date = sdf.parse(str);
  41. } catch (ParseException e) {
  42. e.printStackTrace();
  43. }
  44. return date;
  45. }
  46. //Date 转化Calendar
  47. public static Calendar dateToCalendar(Date date) {
  48. Calendar calendar = Calendar.getInstance();
  49. calendar.setTime(date);
  50. return calendar;
  51. }
  52. //Calendar转化Date
  53. public static Date calendarToDate(Calendar calendar) {
  54. return calendar.getTime();
  55. }
  56. // String 转成 Timestamp
  57. public static Timestamp strToTimeStamp(String str) {
  58. // Timestamp ts = Timestamp.valueOf("2012-1-14 08:11:00");
  59. return Timestamp.valueOf(str);
  60. }
  61. //Date 转 TimeStamp
  62. public static Timestamp dateToTimeStamp(Date date,String format) {
  63. SimpleDateFormat df = new SimpleDateFormat(format);
  64. String time = df.format(new Date());
  65. Timestamp ts = Timestamp.valueOf(time);
  66. return ts;
  67. }
  68. }

4.资源文件

/drawableappoint_calendar_sat_bg.xml //开始时间

  1. <shape xmlns:android="http://schemas.android.com/apk/res/android">
  2. <corners android:topRightRadius="44dp" android:bottomRightRadius="44dp"/>
  3. <size android:height="44dp"/>
  4. <solid android:color="#41D2C4"/>
  5. </shape>

appoint_calendar_sun_bg.xml //结束时间

  1. <shape xmlns:android="http://schemas.android.com/apk/res/android">
  2. <corners
  3. android:bottomLeftRadius="44dp"
  4. android:topLeftRadius="44dp" />
  5. <size android:height="44dp" />
  6. <solid android:color="#41D2C4" />
  7. </shape>

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

  1. <&#63;xml version="1.0" encoding="utf-8"&#63;>
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android" >
  3. <solid android:color="@color/date_duration_bg" />
  4. <corners android:radius="60dp" />
  5. </shape>

/value

  1. <string name="sun"></string>
  2. <string name="mon"></string>
  3. <string name="tue"></string>
  4. <string name="wed"></string>
  5. <string name="thu"></string>
  6. <string name="fri"></string>
  7. <string name="sat"></string>
  8. <color name="date_duration_bg">#41D2C4</color>

5.在activity中使用

activity_selectdate.xml

  1. <&#63;xml version="1.0" encoding="utf-8"&#63;>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. xmlns:app="http://schemas.android.com/apk/res-auto"
  6. android:background="@color/white"
  7. android:orientation="vertical">
  8. <RelativeLayout
  9. android:layout_width="match_parent"
  10. android:layout_height="wrap_content"
  11. android:layout_marginTop="40dp">
  12. <FrameLayout
  13. android:id="@+id/layout_line"
  14. android:layout_width="10dp"
  15. android:layout_height="1dp"
  16. android:layout_centerInParent="true"
  17. android:background="#35C1B5" />
  18. <TextView
  19. android:id="@+id/tv_startime"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:layout_toLeftOf="@+id/layout_line"
  23. android:layout_marginRight="22.5dp"
  24. android:textColor="#35C1B5"
  25. android:textSize="14dp"
  26. android:text="@string/starTime"
  27. />
  28. <TextView
  29. android:id="@+id/tv_endtime"
  30. android:layout_width="wrap_content"
  31. android:layout_height="wrap_content"
  32. android:layout_toRightOf="@+id/layout_line"
  33. android:layout_marginLeft="22.5dp"
  34. android:textColor="#35C1B5"
  35. android:textSize="14dp"
  36. android:text="@string/endTime"
  37. />
  38. </RelativeLayout>
  39. <FrameLayout
  40. android:layout_width="match_parent"
  41. android:layout_height="0.5dp"
  42. android:layout_marginTop="10dp"
  43. android:background="@color/bg_line"
  44. />
  45. <com.包名.CalendarView
  46. android:id="@+id/calendarview"
  47. android:layout_width="match_parent"
  48. android:layout_height="wrap_content"
  49. app:titleColor = "@color/text_lable"
  50. />
  51. </LinearLayout>

SelectTimeActivity.java

  1. public class SelectTimeActivity extends BaseActivity {
  2. @BindView(R.id.tv_title)
  3. TextView tvTitle;
  4. @BindView(R.id.iv_title_back)
  5. ImageView ivTitleBack;
  6. @BindView(R.id.tv_title_left)
  7. TextView tvTitleLeft;
  8. @BindView(R.id.layout_title_left)
  9. RelativeLayout layoutTitleLeft;
  10. @BindView(R.id.tv_title_right)
  11. TextView tvTitleRight;
  12. @BindView(R.id.layout_title_right)
  13. RelativeLayout layoutTitleRight;
  14. @BindView(R.id.layout_line)
  15. FrameLayout layoutLine;
  16. @BindView(R.id.tv_startime)
  17. TextView tvStartime;
  18. @BindView(R.id.tv_endtime)
  19. TextView tvEndtime;
  20. @BindView(R.id.calendarview)
  21. CalendarView calendarview;
  22. private String starTime;
  23. private String endTime;
  24. private boolean isSelecgOk = false;
  25. @Override
  26. protected void onCreate(@Nullable Bundle savedInstanceState) {
  27. super.onCreate(savedInstanceState);
  28. setContentView(R.layout.activity_selectdate);
  29. ButterKnife.bind(this);
  30. setStatusBar(true);
  31. initView();
  32. }
  33. private void initView() {
  34. tvTitle.setText(getString(R.string.selectTime));
  35. ivTitleBack.setVisibility(View.GONE);
  36. tvTitleLeft.setText(getString(R.string.cancel));
  37. tvTitleRight.setText(getString(R.string.confirm));
  38. calendarview.setETimeSelListener(new CalendarView.CalendatEtimSelListener() {
  39. @Override
  40. public void onETimeSelect(Date date) {
  41. if (date != null) {
  42. endTime = DateUtils.formatData(date, Constant.TFORMATE_YMD);
  43. tvEndtime.setText(endTime);
  44. }else {
  45. endTime = null;
  46. }
  47. }
  48. });
  49. calendarview.setSTimeSelListener(new CalendarView.CalendarSTimeSelListener() {
  50. @Override
  51. public void onSTimeSelect(Date date) {
  52. if (date != null) {
  53. starTime = DateUtils.formatData(date, Constant.TFORMATE_YMD);
  54. tvStartime.setText(starTime);
  55. }else {
  56. starTime = null;
  57. }
  58. }
  59. });
  60. calendarview.setCalendaSelListener(new CalendarView.CalendaSelListener() {
  61. @Override
  62. public void selectStatus(boolean isOk) {
  63. isSelecgOk = isOk;
  64. }
  65. });
  66. }
  67. @OnClick({R.id.tv_title_left, R.id.tv_title_right})
  68. public void onClick(View view) {
  69. switch (view.getId()) {
  70. case R.id.tv_title_left:
  71. finish();
  72. break;
  73. case R.id.tv_title_right:
  74. if(TextUtils.isEmpty(starTime)){
  75. ToastUtils.showToast(getString(R.string.history_alert1));
  76. return;
  77. }
  78. if(TextUtils.isEmpty(endTime) || !isSelecgOk){
  79. ToastUtils.showToast(getResources().getString(R.string.history_alert));
  80. return;
  81. }
  82. Intent intent = new Intent();
  83. intent.putExtra("starTime",starTime);
  84. intent.putExtra("endTime",endTime);
  85. setResult(RESULT_OK,intent);
  86. finish();
  87. break;
  88. }
  89. }
  90. }

RecyclerAdapter引用

implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.30'
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/817319
推荐阅读
相关标签
  

闽ICP备14008679号