Skip to content

Instantly share code, notes, and snippets.

@Longwater1234
Last active March 11, 2022 02:46
Show Gist options
  • Save Longwater1234/ac2d79c2eecdc1e2a557f25436ba2d01 to your computer and use it in GitHub Desktop.
Save Longwater1234/ac2d79c2eecdc1e2a557f25436ba2d01 to your computer and use it in GitHub Desktop.
Android DatePicker helper class
/**
* THIS UTILITY CLASS
* HELPS DISPLAY DATEPICKER DIALOG on ANY UI-ELEMENT "onClick".
* @params EditText, Context
*
* @apiNote Example: on a button: Just place this line in your activity's onCreate:
* new SetDateDialog(btnName, ActivityName.this);
*
*/
public class SetDateDialog implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
private final EditText editText;
private static Calendar myCalendar;
private final Context ctx;
public SetDateDialog(EditText editText, Context ctx) {
this.ctx = ctx;
this.editText = editText;
this.editText.setOnClickListener(this);
myCalendar = Calendar.getInstance();
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
String myFormat = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, month);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
editText.setText(sdf.format(myCalendar.getTime()));
}
@Override
public void onClick(View v) {
showDialog();
}
private void showDialog() {
new DatePickerDialog(this.ctx, this,
myCalendar.get(Calendar.YEAR),
myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment