Android日期时间控件选择
informationchina 人气:0前言
整合Android原生控件(日期控件DatePicker、时间控件TimePicker)实现选择日期、时间绑定。
本文仅仅是一种参考,不光是时间控件,自定义的Layout一样可以采用这种方式。
涉及技术要点:
1.控件事件绑定
2.弹出框AlertDialog
3.日期格式化SimpleDateFormat
一、创建弹出Layout
1.1 新建Layout,修改样式为LinearLayout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> </LinearLayout>
1.2 Layout中添加日期和时间控件
注意需要将控件的calendarViewShown指定为false及datePickerMode属性指定为spinner
<?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="wrap_content" android:orientation="vertical"> <DatePicker android:id="@+id/dialog_datetime_date_picker" android:layout_width="match_parent" android:layout_height="wrap_content" android:calendarViewShown="false" android:datePickerMode="spinner"/> <TimePicker android:id="@+id/dialog_datetime_time_picker" android:layout_width="match_parent" android:layout_height="wrap_content" android:calendarViewShown="false" android:datePickerMode="spinner" /> </LinearLayout>
二、新建DateTimeDialog
创建DateTimeDialog类是为了将方法封装,以便我项目多次调用
public class DateTimeDialog { }
2.1 创建静态方法
2.1.1 创建SetDateDialog,用于选择日期
public static void SetDateDialog(Context context, Activity activity, TextView textView, String... title) { }
这里我们将引用控件的context、activity作为参数传入方法中,方便我们动态加载Layout和指定AlertDialog弹出所在的Activity,避免弹出框无法显示。
textView参数为需要绑定选择的控件,并且在选择之后,会将选择的日期返回给textView
titile是可选参数,指定弹出框的标题,不指定的话,会默认为“选择日期”
2.1.2 SetDateDialog中绑定textView的click事件
给textView绑定事件后,在用户点击控件时即可执行相应的事件内容,在此我们需要的是用户点击控件时,弹出日期选择框。
textView.setOnClickListener(view -> { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setView(view1); builder.create().show(); });
由于我们的控件中含有时间控件,需要隐藏
View view1 = LayoutInflater.from(context).inflate(R.layout.dialog_datetime, null); final TimePicker timePicker = view1.findViewById(R.id.dialog_datetime_time_picker); timePicker.setVisibility(View.GONE);
如果textView有默认值,则在弹出的时候需要将textView的日期带入弹出框中
final DatePicker datePicker = view1.findViewById(R.id.dialog_datetime_date_picker); Calendar calendar; String strDate = textView.getText().toString(); calendar = convertDateToCalendar(strDate); datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), null);
设置弹出框的标题
if (title != null && title.length > 0) { builder.setTitle(title[0]); } else builder.setTitle("选择日期");
实现弹出框的按钮事件:
点击确定时,绑定值给textView,并关闭弹窗;点击取消时,直接关闭天窗;点击现在时,将当前时间传给textView,并关闭弹窗。
builder.setPositiveButton("确 定", (dialog, i) -> { //日期格式 int year = datePicker.getYear(); int month = datePicker.getMonth() + 1; int dayOfMonth = datePicker.getDayOfMonth(); textView.setText(String.format(Locale.getDefault(), "%d年%d月%d日 ", year, month, dayOfMonth)); dialog.cancel(); }); builder.setNegativeButton("取 消", (dialog, which) -> dialog.cancel()); builder.setNeutralButton("现 在", (dialog, i) -> { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年M月d日",Locale.getDefault());// HH:mm:ss //获取当前时间 Date date = new Date(System.currentTimeMillis()); textView.setText(simpleDateFormat.format(date)); dialog.cancel(); });
以下是完整代码:
public static void SetDateDialog(Context context, Activity activity, TextView textView, String... title) { textView.setOnClickListener(view -> { AlertDialog.Builder builder = new AlertDialog.Builder(activity); View view1 = LayoutInflater.from(context).inflate(R.layout.dialog_datetime, null); final DatePicker datePicker = view1.findViewById(R.id.dialog_datetime_date_picker); final TimePicker timePicker = view1.findViewById(R.id.dialog_datetime_time_picker); timePicker.setIs24HourView(true); Calendar calendar; String strDate = textView.getText().toString(); calendar = convertDateToCalendar(strDate); datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), null); timePicker.setHour(calendar.get(Calendar.HOUR_OF_DAY)); timePicker.setMinute(calendar.get(Calendar.MINUTE)); timePicker.setVisibility(View.GONE); // datePicker.setCalendarViewShown(false); //设置Date布局 builder.setView(view1); if (title != null && title.length > 0) { builder.setTitle(title[0]); } else builder.setTitle("选择日期"); builder.setPositiveButton("确 定", (dialog, i) -> { //日期格式 int year = datePicker.getYear(); int month = datePicker.getMonth() + 1; int dayOfMonth = datePicker.getDayOfMonth(); textView.setText(String.format(Locale.getDefault(), "%d年%d月%d日 ", year, month, dayOfMonth)); dialog.cancel(); }); builder.setNegativeButton("取 消", (dialog, which) -> dialog.cancel()); builder.setNeutralButton("现 在", (dialog, i) -> { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年M月d日",Locale.getDefault());// HH:mm:ss //获取当前时间 Date date = new Date(System.currentTimeMillis()); textView.setText(simpleDateFormat.format(date)); dialog.cancel(); }); builder.create().show(); }); }
同样的方式我们再实现选择日期时间的方法,具体不再赘述,上代码:
public static void SetDateTimeDialog(Context context, Activity activity, TextView textView, String... title) { textView.setOnClickListener(view -> { AlertDialog.Builder builder = new AlertDialog.Builder(activity); View view1 = LayoutInflater.from(context).inflate(R.layout.dialog_datetime, null); final DatePicker datePicker = view1.findViewById(R.id.dialog_datetime_date_picker); final TimePicker timePicker = view1.findViewById(R.id.dialog_datetime_time_picker); timePicker.setIs24HourView(true); // datePicker.setCalendarViewShown(false); Calendar calendar; String strDate = textView.getText().toString(); calendar = convertDateToCalendar(strDate); datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), null); timePicker.setHour(calendar.get(Calendar.HOUR_OF_DAY)); timePicker.setMinute(calendar.get(Calendar.MINUTE)); //设置Date布局 builder.setView(view1); if (title != null && title.length > 0) { builder.setTitle(title[0]); } else builder.setTitle("选择时间"); 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(); textView.setText(String.format(Locale.getDefault(), "%d年%d月%d日 %d:%d", year, month, dayOfMonth, hour, min)); dialog.cancel(); }); builder.setNegativeButton("取 消", (dialog, which) -> dialog.cancel()); builder.setNeutralButton("现 在", (dialog, i) -> { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年M月d日 HH:mm", Locale.getDefault());// HH:mm:ss //获取当前时间 Date date = new Date(System.currentTimeMillis()); textView.setText(simpleDateFormat.format(date)); dialog.cancel(); }); builder.create().show(); }); }
文中提到的convertDateToCalendar是笔者用于日期转换的,您可以根据自己的需要去灵活实现
private static Calendar convertDateToCalendar(String strDate) { int year; int month; int day; int hour; int minute; Calendar calendar = Calendar.getInstance(); //获取当前时间 Date date = new Date(System.currentTimeMillis()); calendar.setTime(date); // calendar.add(Calendar.MONTH,1); year = calendar.get(Calendar.YEAR); month = calendar.get(Calendar.MONTH); day = calendar.get(Calendar.DATE); hour = calendar.get(Calendar.HOUR_OF_DAY); minute = calendar.get(Calendar.MINUTE); if (strDate != null && !strDate.equals("")) { if (strDate.contains(":")) { strDate = strDate.split(":")[1]; } strDate = strDate.replace("年", "-").replace("月", "-").replace("日", "").replace(".", "").replace(" ", "-").replace(":", "-"); Log.d("liuwz", "convertDateToCalendar: "+strDate); if (strDate.split("-").length >= 3) { year = Integer.parseInt(strDate.split("-")[0]); month = Integer.parseInt(strDate.split("-")[1]); day = Integer.parseInt(strDate.split("-")[2]); if (strDate.split("-").length >= 5) { hour = Integer.parseInt(strDate.split("-")[3]); minute = Integer.parseInt(strDate.split("-")[4]); } calendar.set(year, month, day, hour, minute); calendar.add(Calendar.MONTH, -1); } else if (strDate.split("-").length >= 2) { hour = Integer.parseInt(strDate.split("-")[0]); minute = Integer.parseInt(strDate.split("-")[1]); calendar.set(year, month, day, hour, minute); } } return calendar; }
至此已经大功告成,下面看下如何引用
2.2 引用
在任意需要用到选择时间的Activity的onCreate方法中添加下面一句代码即可:
DateTimeDialog.SetDateDialog(getApplicationContext(), MainActivity.this, timeSelectView, "请选择日期");
将其中的MainActivity修改为您当前的Activity;将timeSelectView 修改为您页面中的时间TextView或者EditView,“请选择日期”为可选参数,可忽略。
三. 总结
本文仅仅为了使用方便而对AlertDialog进行了封装,用的是Android的原生控件,写在此处仅仅给新入门的朋友们以参考。
加载全部内容