I\'ve already got a DatePicker which pops up when the user clicks on the EditText field
eReminderDate.setOnClickListener(new OnClickListener() {
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);
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
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);
}