Code for open date picker dialog(Calendar) in android after clicking on EditText.
Code for open date picker dialog in android.
167622-Aug-2018
Updated on 02-Jul-2023
Home / DeveloperSection / Forums / Code for open date picker dialog in android.
Code for open date picker dialog(Calendar) in android after clicking on EditText.
Aryan Kumar
02-Jul-2023Sure, here is the code for open date picker dialogue in Android:
Code snippet
This code will first create a
DatePickerDialog
object. TheDatePickerDialog
object will be used to display a date picker dialog to the user.The
DatePickerDialog
object has three parameters:The
onDateSet()
method of the listener will be called when the user selects a date. TheonDateSet()
method has three parameters:DatePicker
object that was used to select the date.In the
onDateSet()
method, you can set the date in the text field by calling thesetText()
method of the text field.To use this code, you would need to call the
openDatePickerDialog()
method in your app. For example, you could call the method in your app'sonCreate()
method.Here is an example of how you could call the
openDatePickerDialog()
method in your app'sonCreate()
method:Code snippet
When you run the app, you will see a date picker dialog. You can select a date in the date picker dialog and the date will be displayed in the text field.
Arti Mishra
23-Aug-2018/* get Instance of calendar */
Calendar myCalendar = Calendar.getInstance();
/* Create object of EditText. */
EditText dateOfBirth = (EditText) findViewById(R.id.dob);
/* Set value on date objects*/
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
private void updateLabel() {
String myFormat = "yyyy-MM-dd"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
dateOfBirth.setText(sdf.format(myCalendar.getTime()));
}
/* open Date Picker Dialog for dob*/
dateOfBirth.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new DatePickerDialog(EditProfileActivity.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});