Last active
December 29, 2022 14:07
-
-
Save pratikbutani/a1cf5a6ce8ced6fc302f95ae17bbc94f to your computer and use it in GitHub Desktop.
Android Universal TimePicker to set time with/without AM/PM.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Main file for Time Picker. | |
*/ | |
public class TimePickerUniversal implements View.OnFocusChangeListener, TimePickerDialog.OnTimeSetListener, View.OnClickListener { | |
private EditText mEditText; | |
private Calendar mCalendar; | |
private SimpleDateFormat mFormat; | |
private boolean withAMPM; | |
/** | |
* Constructor | |
* @param editText your EditText | |
* @param withAMPM true if you want AM/PM, false otherwise. | |
*/ | |
public TimePickerUniversal(EditText editText, boolean withAMPM) { | |
this.mEditText = editText; | |
mEditText.setOnFocusChangeListener(this); | |
mEditText.setOnClickListener(this); | |
this.withAMPM = withAMPM; | |
} | |
@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, !withAMPM).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(withAMPM ? "hh:mm a" : "HH:mm", Locale.getDefault()); | |
this.mEditText.setText(mFormat.format(mCalendar.getTime())); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Constructor | |
* @param editText your EditText | |
* @param withAMPM true if you want AM/PM, false otherwise. | |
*/ | |
new TimePickerUniversal(mBinding.startTimeEditText, true); // It will return time with AM/PM like : 10:00 AM | |
new TimePickerUniversal(mBinding.endTimeEditText, false); // It will return simple time like 10:00 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment