Last active
March 11, 2022 02:46
-
-
Save Longwater1234/ac2d79c2eecdc1e2a557f25436ba2d01 to your computer and use it in GitHub Desktop.
Android DatePicker helper class
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
/** | |
* 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