我正在研究日期选择器对话框android。我能够显示所选日期并休息所有工作正常但是当我选择日期,点击确定然后重新打开对话框时,指针返回到最小日期而不是所选日期。我希望它显示最后选择的日期。
我该如何解决这个问题?
当用户点击
时,会打开对话框public void show() {
Calendar now = Calendar.getInstance();
DatePickerDialog dpd = DatePickerDialog.newInstance(
PostInfoUpdate.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
dpd.setMinDate(Calendar.getInstance());
now.add(Calendar.DAY_OF_MONTH, 30);
dpd.setMaxDate(now);
dpd.show(getFragmentManager(), "Datepickerdialog");
}
这是回调方法
@Override
public void onResume() {
super.onResume();
DatePickerDialog dpd
= (DatePickerDialog) getFragmentManager().findFragmentByTag("Datepickerdialog");
if(dpd != null) {
dpd.setOnDateSetListener(this);
}
}
public void setOnDateSetListener(DatePickerDialog.OnDateSetListener listener) {
mCallBack = listener;
}
这是我设置日期的地方
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
String date = "You picked the following date: "+dayOfMonth+"/"+(++monthOfYear)+"/"+year;
dateTextView.setText(date);
}
答案 0 :(得分:1)
当您调用show
方法时,您正在创建Calender
对象的新实例,并将其传递给DatePicker
。因此它将始终显示当前日期。如果要显示所选日期,请使用全局日历对象并将其传递给datePicker,并继续在onDateSet
内更新它。如下所示:
//Global variable, you can initialize inside OnCreate Method
Calendar now = Calendar.getInstance();
public void show() {
DatePickerDialog dpd = DatePickerDialog.newInstance(
PostInfoUpdate.this,
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
dpd.setMinDate(Calendar.getInstance());
now.add(Calendar.DAY_OF_MONTH, 30);
dpd.setMaxDate(now);
dpd.show(getFragmentManager(), "Datepickerdialog");
}
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
String date = "You picked the following date: "+dayOfMonth+"/"+(++monthOfYear)+"/"+year;
dateTextView.setText(date);
now.set(Calendar.YEAR, year);
now.set(Calendar.MONTH, monthOfYear);
now.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}