单击EditText的TimePicker对话框


105

我已经有一个DatePicker,当用户单击EditText字段时,它将弹出

eReminderDate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //To show current date in the datepicker
                Calendar mcurrentDate = Calendar.getInstance();
                int mYear = mcurrentDate.get(Calendar.YEAR);
                int mMonth = mcurrentDate.get(Calendar.MONTH);
                int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog mDatePicker;
                mDatePicker = new DatePickerDialog(AddReminder.this, new OnDateSetListener() {
                    public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
                        // TODO Auto-generated method stub
                    /*      Your code   to get date and time    */
                        selectedmonth = selectedmonth + 1;
                        eReminderDate.setText("" + selectedday + "/" + selectedmonth + "/" + selectedyear);
                    }
                }, mYear, mMonth, mDay);
                mDatePicker.setTitle("Select Date");
                mDatePicker.show();
            }
        });

我尝试以类似的方式进行TimePicker,但无法使其正常工作。这是我尝试使其工作的尝试

 eReminderTime.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Calendar mcurrentTime = Calendar.getInstance();
                int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
                int minute = mcurrentTime.get(Calendar.MINUTE);
                TimePickerDialog mTimePicker;
                mTimePicker = new TimePickerDialog(AddReminder.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                        eReminderTime.setText( ""selectedHour + ":" + selectedMinute);
                    }
                }, hour, minute);
                mTimePicker.setTitle("Select Time");
                mTimePicker.show();

            }
        });

是否有可能像我为DatePicker所做的那样做呢?

我什至尝试使用此代码单击EditText字段后甚至弹出一个TimePicker。

      eReminderTime.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            showDialog(TIME_DIALOG_ID);
        }
    });

由于某种原因,当我将其输入Android Studio时,“ showDialog”被打分。

谁能给我有关我要去哪里的提示?还是我只需要使用自定义DialogFragment?


在您的第二个代码块中什么实际上不起作用?它只是不出现,还是不编译?
Robadob

在setText部分显示“”和selectedHour之间的错误,说需要','或')',但是当我输入',它说“无法解析方法'setText(java.lang.String,java .lang.String)“
Mark O'Sullivan

Answers:


234
eReminderTime.setText( "" + selectedHour + ":" + selectedMinute);

您错过了+介于""选定的小时数与选定的小时数之间的setText方法,它只使用一个字符串,因此您需要将所有部分串联起来(可能不需要使用第一引号)。

eReminderTime.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Calendar mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);
            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(AddReminder.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    eReminderTime.setText( selectedHour + ":" + selectedMinute);
                }
            }, hour, minute, true);//Yes 24 hour time
            mTimePicker.setTitle("Select Time");
            mTimePicker.show();

        }
    });

那应该可以解决第二个错误,因为您没有提供最后一个参数。 TimePickerDialog构造函数


尝试了一下,认为我以前可能会尝试过,因为我之前收到过此消息。现在在“ new TimePickerDialog”之后和“ mTimePicker.setTitle”之前均显示错误。错误是“无法解析构造函数'TimePickerDialog(com.appname.classname,android.app.TimePickerDialog.OnTimeSetListener,int,int)'”
Mark O'Sullivan

2
如果您查看android文档,则需要添加一个最终的布尔参数,说明该对话框是否为24小时。TimePickerDialog(Context context,TimePickerDialog.OnTimeSetListener callBack,int hourOfDay,int minutes,boolean is24HourView)
Robadob

完全忘记了true / false布尔值,早先见过,但是当我将代码更改为类似于日期选择器时忘记了包含它。谢谢你的帮助!
Mark O'Sullivan

3
很好,谢谢。您可能也想格式化分钟:eReminderTime.setText(selectedHour +“:” + String.format(“%02d”,selectedMinute));
斯蒂芬·保罗

我希望它将变得更加有用和可重用-> TimePickerUniversal
Pratik Butani

27

为什么不以可重用的方式书写?

创建SetTime类:

class SetTime implements OnFocusChangeListener, OnTimeSetListener {   

       private EditText editText;
       private Calendar myCalendar;

       public SetTime(EditText editText, Context ctx){
           this.editText = editText;
           this.editText.setOnFocusChangeListener(this);
           this.myCalendar = Calendar.getInstance();

       }

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(hasFocus){
                int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
                int minute = myCalendar.get(Calendar.MINUTE);
                new TimePickerDialog(ctx, this, hour, minute, true).show();
            }
        }

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            // TODO Auto-generated method stub
            this.editText.setText( hourOfDay + ":" + minute);
        }

    }

然后从onCreate函数调用它:

    EditText editTextFromTime = (EditText) findViewById(R.id.editTextFromTime);
    SetTime fromTime = new SetTime(editTextFromTime, this);

如何获得上午/下午?
Pratik Butani

9

您可以在edittext的onclick侦听器中使用以下代码

  TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this,
    new TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay,
                              int minute) {

            tv_time.setText(hourOfDay + ":" + minute);
        }
    }, hour, minute, false);
     timePickerDialog.show();

您可以在Android timepicker示例中查看完整的代码


3

我扩展了@Sumoanand的很好的可重用解决方案,以在多次更改时间时支持焦点更改和单击侦听器。同时更新选择器日历以记住上一次选择的时间+格式化HH:mm

public class TimeSetter implements View.OnFocusChangeListener, TimePickerDialog.OnTimeSetListener, View.OnClickListener {

    private EditText mEditText;
    private Calendar mCalendar;
    private SimpleDateFormat mFormat;

    public TimeSetter(EditText editText){
       this.mEditText = editText;
       mEditText.setOnFocusChangeListener(this);
       mEditText.setOnClickListener(this);
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (hasFocus){
            showPicker(view);
        }
    }

    @Override
    public void onClick(View view) {
        showPicker(view);
    }

    private void showPicker(View view) {
        if (mCalendar == null)
            mCalendar = Calendar.getInstance();

        int hour = mCalendar.get(Calendar.HOUR_OF_DAY);
        int minute = mCalendar.get(Calendar.MINUTE);

        new TimePickerDialog(view.getContext(), this, hour, minute, true).show();
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
        mCalendar.set(Calendar.MINUTE, minute);

        if (mFormat == null)
            mFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());

        this.mEditText.setText(mFormat.format(mCalendar.getTime()));
    }

}

onCreate的用法:

EditText timeEditText = (EditText) rootView.findViewById(R.id.timeText);
new TimeSetter(timeEditText);

谢谢您的解决方案:)我已经对其进行了编辑以用于AM / PM。在这里查看:带有/不带有AM / PM的TimePicker
Pratik Butani

2

我不知道这是否对您有用,对我也很好。

为日期/时间选择器对话框创建一个方法。

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

    // when dialog box is called, below method will be called.
    // The arguments will be working to get the Day of Week to show it in a special TextView for it.

    public void onDateSet(DatePicker view, int selectedYear,
                          int selectedMonth, int selectedDay) {
        String year1 = String.valueOf(selectedYear);
        String month1 = String.valueOf(selectedMonth + 1);
        String day1 = String.valueOf(selectedDay);
        delivDate.setText(month1 + "/" + day1 + "/" + year1);
        delivDay.setText(DateFormat.format("EEEE", new Date(selectedYear, selectedMonth, selectedDay - 1)).toString());
    }
};

然后,无论您想去哪里,都可以像这样

public void setDateOnClick (View view) {
    Calendar cal = Calendar.getInstance();

    DatePickerDialog datePicker = new DatePickerDialog(this, datePickerListener,
            cal.get(Calendar.YEAR),
            cal.get(Calendar.MONTH),
            cal.get(Calendar.DAY_OF_MONTH));
    //Create a cancel button and set the title of the dialog.
    datePicker.setCancelable(false);
    datePicker.setTitle("Select the date");
    datePicker.show();
}

希望您能找到解决方案。


我喜欢两行“ //创建取消按钮[...]”和“ datePicker.setCancelable(false);”。色调色调
MojioMS 2016年

我认为这个问题与这个问题无关。
Pratik Butani

1

您尚未将最后一个参数放在中TimePickerDialog

{
public TimePickerDialog(Context context, OnTimeSetListener listener, int hourOfDay, int minute,
            boolean is24HourView) {
        this(context, 0, listener, hourOfDay, minute, is24HourView);
    }
}

这是的代码TimePickerclass。它需要一个布尔参数is24HourView


0
public void onClick1(View v) {
  DatePickerDialog dialog = new DatePickerDialog(this, this, 2013, 2, 18);
  dialog.show();
}

public void onDateSet1(DatePicker view, int year1, int month1, int day1) {
  e1.setText(day1 + "/" + (month1+1) + "/" + year1);
}

7
请不要只是邮编;解释您的代码在做什么以及为什么它可以解决OP的问题。
dimo414 '16

0
public class **Your java Class** extends ActionBarActivity implements  View.OnClickListener{
date = (EditText) findViewById(R.id.date);
date.setInputType(InputType.TYPE_NULL);
        date.requestFocus();
        date.setOnClickListener(this);
        dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);

        setDateTimeField();

private void setDateTimeField() {
        Calendar newCalendar = Calendar.getInstance();
        fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                date.setText(dateFormatter.format(newDate.getTime()));
            }

        }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));

    }
@Override
    public void onClick(View v) {
        fromDatePickerDialog.show();
    }
}

关于仅此代码答案的一些其他信息可能会有所帮助。
皮夫斯

0

对我来说,如果我多次单击dpFlightDate编辑文本(对于调光对话框),则对话框显示多个对话框。如何避免该对话框仅出现一次,并且如果用户单击第二次,则该对话框一定不能再次出现,即对话框是否出现在屏幕上?

          // perform click event on edit text
            dpFlightDate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // calender class's instance and get current date , month and year from calender
                    final Calendar c = Calendar.getInstance();
                    int mYear = c.get(Calendar.YEAR); // current year
                    int mMonth = c.get(Calendar.MONTH); // current month
                    int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
                    // date picker dialog
                    datePickerDialog = new DatePickerDialog(frmFlightDetails.this,
                            new DatePickerDialog.OnDateSetListener() {
                                @Override
                                public void onDateSet(DatePicker view, int year,
                                                      int monthOfYear, int dayOfMonth) {
                                    // set day of month , month and year value in the edit text
                                    dpFlightDate.setText(dayOfMonth + "/"
                                            + (monthOfYear + 1) + "/" + year);

                                }
                            }, mYear, mMonth, mDay);
                    datePickerDialog.show();
                }
            });
            tpFlightTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Use the current time as the default values for the picker
                    final Calendar c = Calendar.getInstance();
                    int hour = c.get(Calendar.HOUR_OF_DAY);
                    int minute = c.get(Calendar.MINUTE);
                    // Create a new instance of TimePickerDialog
                    timePickerDialog = new TimePickerDialog(frmFlightDetails.this, new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                            tpFlightTime.setText( selectedHour + ":" + selectedMinute);
                        }
                    }, hour, minute, true);//Yes 24 hour time
                    timePickerDialog.setTitle("Select Time");
                    timePickerDialog.show();
                }
            });
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.