0


Android开发之日期时间控件选择

Android开发之日期时间控件选择

文章目录


前言

整合Android原生控件(日期控件DatePicker、时间控件TimePicker)实现选择日期、时间绑定。
本文仅仅是一种参考,不光是时间控件,自定义的Layout一样可以采用这种方式。
涉及技术要点:
1.控件事件绑定
2.弹出框AlertDialog
3.日期格式化SimpleDateFormat
弹出效果图


一、创建弹出Layout

1.1 新建Layout,修改样式为LinearLayout

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="wrap_content"
  4. android:orientation="vertical"></LinearLayout>

1.2 Layout中添加日期和时间控件

注意需要将控件的calendarViewShown指定为false及datePickerMode属性指定为spinner

  1. <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="wrap_content"
  4. android:orientation="vertical"><DatePicker
  5. android:id="@+id/dialog_datetime_date_picker"
  6. android:layout_width="match_parent"
  7. android:layout_height="wrap_content"
  8. android:calendarViewShown="false"
  9. android:datePickerMode="spinner"/><TimePicker
  10. android:id="@+id/dialog_datetime_time_picker"
  11. android:layout_width="match_parent"
  12. android:layout_height="wrap_content"
  13. android:calendarViewShown="false"
  14. android:datePickerMode="spinner"/></LinearLayout>

二、新建DateTimeDialog

创建DateTimeDialog类是为了将方法封装,以便我项目多次调用

  1. public class DateTimeDialog {}

2.1 创建静态方法

2.1.1 创建SetDateDialog,用于选择日期

  1. public staticvoidSetDateDialog(Context context, Activity activity, TextView textView, String... title){}

这里我们将引用控件的context、activity作为参数传入方法中,方便我们动态加载Layout和指定AlertDialog弹出所在的Activity,避免弹出框无法显示。
textView参数为需要绑定选择的控件,并且在选择之后,会将选择的日期返回给textView
titile是可选参数,指定弹出框的标题,不指定的话,会默认为“选择日期”

2.1.2 SetDateDialog中绑定textView的click事件

给textView绑定事件后,在用户点击控件时即可执行相应的事件内容,在此我们需要的是用户点击控件时,弹出日期选择框。

  1. textView.setOnClickListener(view ->{
  2. AlertDialog.Builder builder = new AlertDialog.Builder(activity);
  3. builder.setView(view1);
  4. builder.create().show();});

由于我们的控件中含有时间控件,需要隐藏

  1. View view1 = LayoutInflater.from(context).inflate(R.layout.dialog_datetime, null);
  2. final TimePicker timePicker = view1.findViewById(R.id.dialog_datetime_time_picker);
  3. timePicker.setVisibility(View.GONE);

如果textView有默认值,则在弹出的时候需要将textView的日期带入弹出框中

  1. final DatePicker datePicker = view1.findViewById(R.id.dialog_datetime_date_picker);
  2. Calendar calendar;
  3. String strDate = textView.getText().toString();
  4. calendar =convertDateToCalendar(strDate);
  5. datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), null);

设置弹出框的标题

  1. if(title != null && title.length >0){
  2. builder.setTitle(title[0]);}else
  3. builder.setTitle("选择日期");

实现弹出框的按钮事件:
点击确定时,绑定值给textView,并关闭弹窗;点击取消时,直接关闭天窗;点击现在时,将当前时间传给textView,并关闭弹窗。

  1. builder.setPositiveButton("确 定",(dialog, i)->{//日期格式int year = datePicker.getYear();int month = datePicker.getMonth()+1;int dayOfMonth = datePicker.getDayOfMonth();
  2. textView.setText(String.format(Locale.getDefault(),"%d年%d月%d日 ", year, month, dayOfMonth));
  3. dialog.cancel();});
  4. builder.setNegativeButton("取 消",(dialog, which)-> dialog.cancel());
  5. builder.setNeutralButton("现 在",(dialog, i)->{
  6. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年M月d日",Locale.getDefault());// HH:mm:ss//获取当前时间
  7. Date date = new Date(System.currentTimeMillis());
  8. textView.setText(simpleDateFormat.format(date));
  9. dialog.cancel();});

以下是完整代码:

  1. public staticvoidSetDateDialog(Context context, Activity activity, TextView textView, String... title){
  2. textView.setOnClickListener(view ->{
  3. AlertDialog.Builder builder = new AlertDialog.Builder(activity);
  4. View view1 = LayoutInflater.from(context).inflate(R.layout.dialog_datetime, null);
  5. final DatePicker datePicker = view1.findViewById(R.id.dialog_datetime_date_picker);
  6. final TimePicker timePicker = view1.findViewById(R.id.dialog_datetime_time_picker);
  7. timePicker.setIs24HourView(true);
  8. Calendar calendar;
  9. String strDate = textView.getText().toString();
  10. calendar =convertDateToCalendar(strDate);
  11. datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), null);
  12. timePicker.setHour(calendar.get(Calendar.HOUR_OF_DAY));
  13. timePicker.setMinute(calendar.get(Calendar.MINUTE));
  14. timePicker.setVisibility(View.GONE);// datePicker.setCalendarViewShown(false);//设置Date布局
  15. builder.setView(view1);if(title != null && title.length >0){
  16. builder.setTitle(title[0]);}else
  17. builder.setTitle("选择日期");
  18. builder.setPositiveButton("确 定",(dialog, i)->{//日期格式int year = datePicker.getYear();int month = datePicker.getMonth()+1;int dayOfMonth = datePicker.getDayOfMonth();
  19. textView.setText(String.format(Locale.getDefault(),"%d年%d月%d日 ", year, month, dayOfMonth));
  20. dialog.cancel();});
  21. builder.setNegativeButton("取 消",(dialog, which)-> dialog.cancel());
  22. builder.setNeutralButton("现 在",(dialog, i)->{
  23. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年M月d日",Locale.getDefault());// HH:mm:ss//获取当前时间
  24. Date date = new Date(System.currentTimeMillis());
  25. textView.setText(simpleDateFormat.format(date));
  26. dialog.cancel();});
  27. builder.create().show();});}

同样的方式我们再实现选择日期时间的方法,具体不再赘述,上代码:

  1. public staticvoidSetDateTimeDialog(Context context, Activity activity, TextView textView, String... title){
  2. textView.setOnClickListener(view ->{
  3. AlertDialog.Builder builder = new AlertDialog.Builder(activity);
  4. View view1 = LayoutInflater.from(context).inflate(R.layout.dialog_datetime, null);
  5. final DatePicker datePicker = view1.findViewById(R.id.dialog_datetime_date_picker);
  6. final TimePicker timePicker = view1.findViewById(R.id.dialog_datetime_time_picker);
  7. timePicker.setIs24HourView(true);// datePicker.setCalendarViewShown(false);
  8. Calendar calendar;
  9. String strDate = textView.getText().toString();
  10. calendar =convertDateToCalendar(strDate);
  11. datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), null);
  12. timePicker.setHour(calendar.get(Calendar.HOUR_OF_DAY));
  13. timePicker.setMinute(calendar.get(Calendar.MINUTE));//设置Date布局
  14. builder.setView(view1);if(title != null && title.length >0){
  15. builder.setTitle(title[0]);}else
  16. builder.setTitle("选择时间");
  17. builder.setPositiveButton("确 定",(dialog, i)->{//日期格式int year = datePicker.getYear();int month = datePicker.getMonth()+1;int dayOfMonth = datePicker.getDayOfMonth();int hour = timePicker.getHour();int min = timePicker.getMinute();// timePicker.getSecond();
  18. textView.setText(String.format(Locale.getDefault(),"%d年%d月%d日 %d:%d", year, month, dayOfMonth, hour, min));
  19. dialog.cancel();});
  20. builder.setNegativeButton("取 消",(dialog, which)-> dialog.cancel());
  21. builder.setNeutralButton("现 在",(dialog, i)->{
  22. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年M月d日 HH:mm", Locale.getDefault());// HH:mm:ss//获取当前时间
  23. Date date = new Date(System.currentTimeMillis());
  24. textView.setText(simpleDateFormat.format(date));
  25. dialog.cancel();});
  26. builder.create().show();});}

文中提到的convertDateToCalendar是笔者用于日期转换的,您可以根据自己的需要去灵活实现

  1. private static Calendar convertDateToCalendar(String strDate){int year;int month;int day;int hour;int minute;
  2. Calendar calendar = Calendar.getInstance();//获取当前时间
  3. Date date = new Date(System.currentTimeMillis());
  4. calendar.setTime(date);// calendar.add(Calendar.MONTH,1);
  5. year = calendar.get(Calendar.YEAR);
  6. month = calendar.get(Calendar.MONTH);
  7. day = calendar.get(Calendar.DATE);
  8. hour = calendar.get(Calendar.HOUR_OF_DAY);
  9. minute = calendar.get(Calendar.MINUTE);if(strDate != null &&!strDate.equals("")){if(strDate.contains(":")){
  10. strDate = strDate.split(":")[1];}
  11. strDate = strDate.replace("年","-").replace("月","-").replace("日","").replace(".","").replace(" ","-").replace(":","-");
  12. Log.d("liuwz","convertDateToCalendar: "+strDate);if(strDate.split("-").length >=3){
  13. year = Integer.parseInt(strDate.split("-")[0]);
  14. month = Integer.parseInt(strDate.split("-")[1]);
  15. day = Integer.parseInt(strDate.split("-")[2]);if(strDate.split("-").length >=5){
  16. hour = Integer.parseInt(strDate.split("-")[3]);
  17. minute = Integer.parseInt(strDate.split("-")[4]);}
  18. calendar.set(year, month, day, hour, minute);
  19. calendar.add(Calendar.MONTH,-1);}elseif(strDate.split("-").length >=2){
  20. hour = Integer.parseInt(strDate.split("-")[0]);
  21. minute = Integer.parseInt(strDate.split("-")[1]);
  22. calendar.set(year, month, day, hour, minute);}}return calendar;}

至此已经大功告成,下面看下如何引用

2.2 引用

在任意需要用到选择时间的Activity的onCreate方法中添加下面一句代码即可:

  1. DateTimeDialog.SetDateDialog(getApplicationContext(), MainActivity.this, timeSelectView,"请选择日期");

将其中的MainActivity修改为您当前的Activity;将timeSelectView 修改为您页面中的时间TextView或者EditView,“请选择日期”为可选参数,可忽略。

三. 总结

本文仅仅为了使用方便而对AlertDialog进行了封装,用的是Android的原生控件,写在此处仅仅给新入门的朋友们以参考。


本文转载自: https://blog.csdn.net/informationchina/article/details/125065813
版权归原作者 informationchina 所有, 如有侵权,请联系我们删除。

“Android开发之日期时间控件选择”的评论:

还没有评论