在android中的一个对话框中创建日期和时间选择器

时间:2015-04-30 10:44:24

标签: android dialog

在问题标题中,我想在android中的一个对话框中显示日期和时间选择器。也许显示第一个datepicker,在用户选择一个日期后,它应该在没有关闭的情况下过渡时间戳并重新打开对话框。

怎么做? 感谢

2 个答案:

答案 0 :(得分:2)

你可以在Pre-Lollipop设备上使用材质设计的thar库,它是如此美丽的图书馆。

https://github.com/flavienlaurent/datetimepicker

时间选择器令人惊叹。

答案 1 :(得分:-1)

//我的日期和时间选择器样式 //日期选择器

private SimpleDateFormat dateFormat,timeFormat;
dateFormat =new SimpleDateFormat("EEEE,MMM d");
timeFormat = new SimpleDateFormat("HH:mm a");

//我的onclick

@Override
public void onClick(View v) {
    if (v.getId()==R.id.dob){
        openDatePicker(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar calendar=Calendar.getInstance();
                calendar.set(Calendar.YEAR,year);
                calendar.set(Calendar.MONTH,monthOfYear);
                calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);
                String dateString=formatDate(calendar.getTimeInMillis());
                dob.setText(dateString);
            }
        });
    }

// opendatepicker方法

private  String formatDate(long timeStamp){
    Date date =new Date(timeStamp);
    String dateToShow = dateFormat.format(date);
    return dateToShow;
}
private void openDatePicker(DatePickerDialog.OnDateSetListener listner){
    Calendar calendar=Calendar.getInstance();
    new DatePickerDialog(this,listner,calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show();
}

//和时间选择器

if (v.getId()==R.id.time){
        openTimePicker(new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                String time=getStringTime(hourOfDay,minute);
                textTime.setText(time);
            }
        });
    }

// opentimepickermethod

private void openTimePicker(TimePickerDialog.OnTimeSetListener listner){
    Date date=new Date();
    new TimePickerDialog(this,listner,date.getHours(),date.getMinutes(),false).show();
}

private String getStringTime(int hour,int minute){
    String am_pm="";
    Calendar calendar=Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, minute);
    if(calendar.get(Calendar.AM_PM)==Calendar.AM){
        am_pm="AM";
        return ""+calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUTE)+""+am_pm;
    }else{
        am_pm="PM";
        if(calendar.get(Calendar.HOUR)==0) {
            hour = 12;
            return "" + hour + ":" + calendar.get(Calendar.MINUTE) + "" + am_pm;
        }else
            return ""+calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUTE)+""+am_pm;

    }

}