我希望将DatePickerDialog
的值设置到EditText
中,使用(sdf.format(myCalendar.getTime()));
。我已经尝试了这种方法,但没有成功。应该如何修复呢?
以下是我的代码:
Calendar myCalendar;
DatePickerDialog.OnDateSetListener date;
private int pYear;
private int pMonth;
private int pDay;
static final int DATE_DIALOG_ID = 0;
myCalendar = Calendar.getInstance();
pYear = myCalendar.get(Calendar.YEAR);
pMonth = myCalendar.get(Calendar.MONTH);
pDay = myCalendar.get(Calendar.DAY_OF_MONTH);
dobET.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(DATE_DIALOG_ID);
}
});
public Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
date = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
pYear = year;
pMonth = monthOfYear;
pDay = dayOfMonth;
updateLabel();
}
};
DatePickerDialog dialog = new DatePickerDialog(this, date, pYear, pMonth, pDay);
dialog.getDatePicker().setMaxDate(new Date().getTime());
return dialog;
}
return null;
}
private void updateLabel() {
String myFormat = "MM-dd-yyyy"; // In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
String myFormat2 = "yyyy-MM-dd"; // In which you need put here
SimpleDateFormat sdf2 = new SimpleDateFormat(myFormat2, Locale.US);
dateToSave = sdf2.format(myCalendar.getTime());
saveDOBPrefEditor.putString("DOB", dateToSave);
saveDOBPrefEditor.commit();
dobET.setText(sdf.format(myCalendar.getTime()));
}
onDateSet()
中更新了pBlaBla
,但是在updateLabel()
中使用了myCalendar
。请更新其中一个变量,并在updateLabel()
中使用它们。 - Andrew T.showDialog(DATE_DIALOG_ID);
方法已经过时。您应该使用DatePickerDialogFragment
。 - PiyushonDateSet()
。 - Andrew T.