效果图:
代码:Fragment.java或Activity.java
//开始日期
textView_setBeginDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialogPick(textView_beginDate);//将textView传入用于显示所选择的时间
}
});
//函数:选择日期->选择时间(先后)
private void showDialogPick(final TextView timeText) {
final StringBuffer time = new StringBuffer();
//获取Calendar对象,用于获取当前时间
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
//实例化TimePickerDialog对象——TimePickerDialog用于选择时间
final TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
//参数2:回调函数——选择完时间后会调用
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
time.append(" ").append(hourOfDay < 10 ? "0" + hourOfDay : "" + hourOfDay)
.append(":").append(minute < 10 ? "0" + minute : ""+ minute); //格式化时钟
//设置TextView显示最终选择的时间
timeText.setText(time);
}
}, hour, minute, true);//参数3、4:初始化的时间
//实例化DatePickerDialog对象——DatePickerDialog用于选择日期
DatePickerDialog datePickerDialog = new DatePickerDialog(Objects.requireNonNull(getActivity()), new DatePickerDialog.OnDateSetListener() {
//参数2:回调函数——选择完日期后会调用
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//因为monthOfYear起始值为0,所以这边要加1
time.append(year).append("年").append(monthOfYear + 1).append("月").append(dayOfMonth).append("日");
timePickerDialog.show();//2)选择完日期后弹出选择时间对话框
}
}, year, month, day);//参数3、4、5:初始化的时间
//1)弹出日期选择对话框
datePickerDialog.show();
}
参考文章:android选择时间攻略 https://www.jianshu.com/p/252b355be7ca
另外一种样式:
参考链接:https://blog.csdn.net/liuwan1992/article/details/52701475