热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

Android日历控件的实现方法

这篇文章主要为大家详细介绍了Android如何打造自己的日历控件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Android日历控件的实现代码,供大家参考,具体内容如下

1、效果图:

2、弹窗Dialog:SelectDateDialog:

public class SelectDateDialog {

 private static final String TAG = "SelectDateDialog";

 private Dialog dialog;
 private TextView dateText;
 private int selectYear, selectMonth;
 private AppCompatActivity mContext;
 private DateAdapter adapter;
 private List selWeekList = new ArrayList<>();
 private List list = new ArrayList<>();

 public SelectDateDialog builder(AppCompatActivity mContext, int year, int month) {
 this.mCOntext= mContext;
 this.selectYear = year;
 this.selectMOnth= month;
 // 获取Dialog布局
 View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_date, null);

 // 定义Dialog布局和参数
 dialog = new Dialog(mContext, R.style.AlertDialogStyle);
 dialog.setCanceledOnTouchOutside(false);//点击外部是否取消
 dialog.setCancelable(false);
 dialog.setContentView(view);
 Window window = dialog.getWindow();
 WindowManager.LayoutParams params = window.getAttributes();
 params.width = (ScreenUtils.getScreenWidth(mContext));
// params.height = (int) (ScreenUtils.getScreenHeight(mContext) * 0.5);
 window.setAttributes(params);
 window.setGravity(Gravity.BOTTOM);

 RecyclerView recycler = view.findViewById(R.id.recycler_select_date);
 dateText = view.findViewById(R.id.date_text);
 dateText.setText(year + "年" + month + "月");
 //下个月
 view.findViewById(R.id.next_month).setOnClickListener(view13 -> {
 if (selectMonth > 11) {
 selectYear = selectYear + 1;
 selectMOnth= 1;
 } else {
 selectMonth++;
 }
 showNewData(selectYear, selectMonth);
 });
 //上个月
 view.findViewById(R.id.last_month).setOnClickListener(view14 -> {
 if (selectMonth <2) {
 selectYear = selectYear - 1;
 selectMOnth= 12;
 } else {
 selectMonth--;
 }
 showNewData(selectYear, selectMonth);
 });

 list = DataUtils.getCalendar(year, month);
 adapter = new DateAdapter(mContext, list);
 GridLayoutManager manager = new GridLayoutManager(mContext, 7);
 recycler.setLayoutManager(manager);
 recycler.setAdapter(adapter);
 //取消
 view.findViewById(R.id.middle_cancel).setOnClickListener(view1 -> {
 dialog.dismiss();
 });
 //确定
 view.findViewById(R.id.middle_determine).setOnClickListener(view1 -> {
 initSelect();
 });
 //设置选中当天
 adapter.setNowDay(year, month, DataUtils.getLastMonth(year, month));
 return this;
 }

 private void showNewData(int year, int month) {
 list = DataUtils.getCalendar(year, month);
 //更新月数据
 adapter.setList(list);
 adapter.setNowDay(year , month, DataUtils.getLastMonth(year, month));
 dateText.setText(year + "年" + month + "月");
 }

 /**
 * 获取选中的日期
 */
 private void initSelect() {
 selWeekList.clear();
 for (int i = 0; i 

ScreenUtils:

public class ScreenUtils {

 public static int getScreenWidth(Context context) {
 DisplayMetrics localDisplayMetrics = new DisplayMetrics();
 ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(localDisplayMetrics);
 return localDisplayMetrics.widthPixels;
 }
}

DateBean:

public class DateBean {

 private int week;
 private boolean sign;
 //0 上月 1本月 2下月
 private int month;
 private boolean isFlag;

 public boolean isFlag() {
 return isFlag;
 }

 public void setFlag(boolean flag) {
 isFlag = flag;
 }

 public int getWeek() {
 return week;
 }

 public void setWeek(int week) {
 this.week = week;
 }

 public boolean isSign() {
 return sign;
 }

 public void setSign(boolean sign) {
 this.sign = sign;
 }

 public int getMonth() {
 return month;
 }

 public void setMonth(int month) {
 this.mOnth= month;
 }

 public DateBean(int week, boolean sign, int month) {
 this.week = week;
 this.sign = sign;
 this.mOnth= month;
 }
}

适配器:DateAdapter

public class DateAdapter extends CommonRecyclerAdapter {

 private static final String TAG = "DateAdapter";
 private Integer nowDay;
 private int year;
 private int month;

 public DateAdapter(Context context, List list) {
 super(context, R.layout.item_date, list);
 }

 public void setNowDay(int year, int month, int nowDay) {
 this.nowDay = nowDay;
 this.year = year;
 this.mOnth= month;
 notifyDataSetChanged();
 }

 @Override
 public void convert(RecyclerHolder holder, DateBean item, int position) {

 TextView number = holder.getView(R.id.item_number);
 number.setText(item.getWeek() + "");

 //当前年月等于切换年月时才选中当天
 if (position == nowDay) {
 String date = year + "-" + month;
 if (date.equals(DataUtils.timeInMillsTrasToDate(1))) {
 number.setBackgroundResource(R.drawable.date_unsel_shape);
 number.setTextColor(Color.WHITE);
 }else {
 number.setTextColor(Color.parseColor("#333333"));
 }
 } else {
 number.setBackgroundResource(0);
 number.setTextColor(Color.parseColor("#333333"));
 if (item.getMonth() == 0 || item.getMonth() == 2) {
 number.setTextColor(Color.parseColor("#CDCDCD"));
 } else {
 number.setTextColor(Color.parseColor("#333333"));
 }
 }
 //点击事件
 number.setOnClickListener(view -> {
 //本月可以点击
 int nowYear = Integer.parseInt(DataUtils.timeInMillsTrasToDate(2));
 int nowMOnth= Integer.parseInt(DataUtils.timeInMillsTrasToDate(3));
 //只有在今天之后的日期才可以选中
 if (year == nowYear) {
 if (item.getMonth() == 1 && mOnth== nowMonth && position > nowDay) {
 onClick(item, number);
 } else if (month > nowMonth) {
 onClick(item, number);
 }
 } else if (year > nowYear) {
 onClick(item, number);
 }
 });
 }

 private void onClick(DateBean item, TextView number) {
 if (item.isFlag()) {
 item.setFlag(false);
 number.setBackgroundResource(0);
 number.setTextColor(Color.parseColor("#333333"));
 } else {
 item.setFlag(true);
 number.setBackgroundResource(R.drawable.date_sel_shape);
 number.setTextColor(Color.WHITE);
 }
 }
}

注意:CommonRecyclerAdapter之前写过,这里不再重复

数据源:DataUtils

public class DataUtils {

 private static final String TAG = "DataUtils";

 /**
 * 日历
 */
 public static List getCalendar(int currentYear, int currentMonth) {
 //实例化集合
 List list = new ArrayList<>();
 Calendar c = Calendar.getInstance();
 c.clear();
 /**
 * 处理上个月月末
 */
 if (currentMonth - 1 == 0) {
 c.set(Calendar.YEAR, currentYear - 1);
 c.set(Calendar.MONTH, 11);
 } else {
 c.set(Calendar.YEAR, currentYear);
 c.set(Calendar.MONTH, (currentMonth - 2));
 }
 int last_sumDays = c.getActualMaximum(Calendar.DAY_OF_MONTH);
 c.set(Calendar.DATE, last_sumDays);
 //得到一号星期几
 int weekDay = c.get(Calendar.DAY_OF_WEEK);
 if (weekDay <7) {
 for (int i = weekDay - 1; i >= 0; i--) {
 Integer date = new Integer(last_sumDays - i);
 list.add(new DateBean(date, true, 0));
 }
 }
 /**
 * 处理当前月
 */
 c.clear();
 c.set(Calendar.YEAR, currentYear);
 c.set(Calendar.MONTH, currentMonth - 1);
 int currentsumDays = c.getActualMaximum(Calendar.DAY_OF_MONTH);
 for (int i = 1; i <= currentsumDays; i++) {
 Integer date = new Integer(i);
 list.add(new DateBean(date, true, 1));
 }
 /**
 * 处理下个月月初
 */
 c.clear();
 if (currentMOnth== 12) {
 c.set(Calendar.YEAR, currentYear + 1);
 c.set(Calendar.MONTH, 0);
 } else {
 c.set(Calendar.YEAR, currentYear);
 c.set(Calendar.MONTH, currentMonth);
 }
 c.set(Calendar.DATE, 1);
 int currentWeekDay = c.get(Calendar.DAY_OF_WEEK);
 if (currentWeekDay > 2 && currentWeekDay <8) {
 for (int i = 1; i <= 8 - currentWeekDay; i++) {
 list.add(new DateBean(i, true, 2));
 }
 }
 return list;
 }

 /**
 * 获取上个月大小
 */
 public static Integer getLastMonth(int currentYear, int currentMonth) {
 //实例化集合
 List list = new ArrayList<>();
 Calendar c = Calendar.getInstance();
 c.clear();
 /**
 * 处理上个月月末
 */
 if (currentMonth - 1 == 0) {
 c.set(Calendar.YEAR, currentYear - 1);
 c.set(Calendar.MONTH, 11);
 } else {
 c.set(Calendar.YEAR, currentYear);
 c.set(Calendar.MONTH, (currentMonth - 2));
 }
 int last_sumDays = c.getActualMaximum(Calendar.DAY_OF_MONTH);
 c.set(Calendar.DATE, last_sumDays);
 //得到一号星期几
 int weekDay = c.get(Calendar.DAY_OF_WEEK);
 if (weekDay <7) {
 for (int i = weekDay - 1; i >= 0; i--) {
 list.add(i);
 }
 }
 Log.e(TAG, "getLastMonth: " + Integer.parseInt(timeInMillsTrasToDate(0)));
 return list.size() + Integer.parseInt(timeInMillsTrasToDate(0)) - 1;
 }

 /**
 * list转string字符串
 */
 public static String returnList(List list) {
 if (null == list && list.size() == 0) {
 return "";
 } else {
 //去除空格
 String str = String.valueOf(list).replaceAll(" ", "");
 return str.substring(1, str.length() - 1);
 }
 }

 /**
 * 时间转换
 */
 @TargetApi(Build.VERSION_CODES.N)
 public static String timeInMillsTrasToDate(int formatType) {
 DateFormat formatter = null;
 switch (formatType) {
 case 0:
 formatter = new SimpleDateFormat("dd");
 break;
 case 1:
 formatter = new SimpleDateFormat("yyyy-MM");
 break;
 case 2:
 formatter = new SimpleDateFormat("yyyy");
 break;
 case 3:
 formatter = new SimpleDateFormat("MM");
 break;
 }
 Calendar calendar = Calendar.getInstance();
 return formatter.format(calendar.getTime());
 }
}

使用:DateActivity

public class DateActivity extends AppCompatActivity {

 private Button openDate;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_date);
 openDate = this.findViewById(R.id.open_date);
 openDate.setOnClickListener(view -> {
 showDateDialog();
 });
 }

 private void showDateDialog() {
 int year = Integer.parseInt(DataUtils.timeInMillsTrasToDate(2));
 int mOnth= Integer.parseInt(DataUtils.timeInMillsTrasToDate(3));
 new SelectDateDialog().builder(this, year, month)
 .setListener(selectDate -> openDate.setText(selectDate)).show();

 }
}

对应布局:activity_date

<&#63;xml version="1.0" encoding="utf-8"&#63;>


 

2、资源文件:

date_sel_shape.xml

<&#63;xml version="1.0" encoding="utf-8"&#63;>


 

 
 

date_unsel_shape.xml

<&#63;xml version="1.0" encoding="utf-8"&#63;>


 

 
 

dialog_shape.xml

<&#63;xml version="1.0" encoding="utf-8"&#63;>


 

 

item_date.xml:

<&#63;xml version="1.0" encoding="utf-8"&#63;>


 

颜色:

#008577
#00574B
#D81B60

样式:


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


推荐阅读
  • 本文介绍了使用kotlin实现动画效果的方法,包括上下移动、放大缩小、旋转等功能。通过代码示例演示了如何使用ObjectAnimator和AnimatorSet来实现动画效果,并提供了实现抖动效果的代码。同时还介绍了如何使用translationY和translationX来实现上下和左右移动的效果。最后还提供了一个anim_small.xml文件的代码示例,可以用来实现放大缩小的效果。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文讲述了如何通过代码在Android中更改Recycler视图项的背景颜色。通过在onBindViewHolder方法中设置条件判断,可以实现根据条件改变背景颜色的效果。同时,还介绍了如何修改底部边框颜色以及提供了RecyclerView Fragment layout.xml和项目布局文件的示例代码。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • eclipse学习(第三章:ssh中的Hibernate)——11.Hibernate的缓存(2级缓存,get和load)
    本文介绍了eclipse学习中的第三章内容,主要讲解了ssh中的Hibernate的缓存,包括2级缓存和get方法、load方法的区别。文章还涉及了项目实践和相关知识点的讲解。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • Java验证码——kaptcha的使用配置及样式
    本文介绍了如何使用kaptcha库来实现Java验证码的配置和样式设置,包括pom.xml的依赖配置和web.xml中servlet的配置。 ... [详细]
  • HDFS2.x新特性
    一、集群间数据拷贝scp实现两个远程主机之间的文件复制scp-rhello.txtroothadoop103:useratguiguhello.txt推pushscp-rr ... [详细]
  • Android系统移植与调试之如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
    本文介绍了如何修改Android设备状态条上音量加减键在横竖屏切换时的显示与隐藏。通过修改系统文件system_bar.xml实现了该功能,并分享了解决思路和经验。 ... [详细]
  • 本文介绍了Android 7的学习笔记总结,包括最新的移动架构视频、大厂安卓面试真题和项目实战源码讲义。同时还分享了开源的完整内容,并提醒读者在使用FileProvider适配时要注意不同模块的AndroidManfiest.xml中配置的xml文件名必须不同,否则会出现问题。 ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • 本文是关于自学Android的笔记,包括查看类的源码的方法,活动注册的必要性以及布局练习的重要性。通过学习本文,读者可以了解到在自学Android过程中的一些关键点和注意事项。 ... [详细]
  • 突破MIUI14限制,自定义胶囊图标、大图标样式,支持任意APP
    本文介绍了如何突破MIUI14的限制,实现自定义胶囊图标和大图标样式,并支持任意APP。需要一定的动手能力和主题设计师账号权限或者会主题pojie。详细步骤包括应用包名获取、素材制作和封包获取等。 ... [详细]
author-avatar
夏天
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有