TimePicker Dialog from clicking EditText

AndroidAndroid Timepicker

Android Problem Overview


I've already got a DatePicker which pops up when the user clicks on the EditText field

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();
            }
        });

I've tried doing a TimePicker in a similar way but was unable to get it working. This is my attempt at getting it working

 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();

            }
        });

Is it impossible to do it similar to the way I did it for DatePicker?

I've tried even just making a TimePicker pop up once the EditText field is clicked with this code.

      eReminderTime.setOnClickListener(new OnClickListener() {

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

For some reason when I entered that into Android Studio the 'showDialog' was scored out.

Can anyone give me tips on where I'm going wrong? Or am I just going to have to use a Custom DialogFragment?

Android Solutions


Solution 1 - Android

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

Your missing a + between "" and selected hour, setText methods only take a single string, so you need to concatenate all the parts (the first quotes are likely unnecessary).

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();

        }
    });

That should fix your second error, you weren't providing the last parameter. TimePickerDialog Constructors

Solution 2 - Android

Why not write in a re-usable way ?

Create SetTime class:

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);
		}
	
	}

Then call it from onCreate function:

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

Solution 3 - Android

You can use the below code in the onclick listener of edittext

  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();

You can see the full code at Android timepicker example

Solution 4 - Android

I extended the nice reusable solution of @Sumoanand to support both focus change and click listeners when changing the time multiple times. Also updating the picker calendar to remember the last selected time + formatting 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()));
    }

}

Usage from onCreate:

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

Solution 5 - Android

I dont know if this will work for you, it works for me just fine.

Create a method for the Date/Time picker dialog.

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());
    }
};

and then, wherever you want you can do it just like this

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();
}

hope you find this as your solution.

Solution 6 - Android

You have not put the last argument in the TimePickerDialog.

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

this is the code of the TimePickerclass. it requires a boolean argument is24HourView

Solution 7 - Android

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);
}

Solution 8 - Android

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();
    }
}

Solution 9 - Android

For me the dialogue appears more than one if I click the dpFlightDate edit text more than one time same for the timmer dialog . how can I avoid this dialog to appear only once and if the user click's 2nd time the dialog must not appear again ie if dialog is on the screen ?

          // 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();
                }
            });

Solution 10 - Android

In all of the above, the EditText still needs the focusable="false" attribute in the xml in order to prevent the keyboard from popping up.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark O'SullivanView Question on Stackoverflow
Solution 1 - AndroidRobadobView Answer on Stackoverflow
Solution 2 - AndroidSumoanandView Answer on Stackoverflow
Solution 3 - AndroidRameesView Answer on Stackoverflow
Solution 4 - Androidpeter.bartosView Answer on Stackoverflow
Solution 5 - AndroidMigue AguirreView Answer on Stackoverflow
Solution 6 - AndroidswatiView Answer on Stackoverflow
Solution 7 - Androidvirendra singh deoraView Answer on Stackoverflow
Solution 8 - AndroidJezrel JumwaView Answer on Stackoverflow
Solution 9 - AndroidJerry AbrahamView Answer on Stackoverflow
Solution 10 - AndroidMGLabsView Answer on Stackoverflow