我有一个我在 onCreate 中定义的日期选择器的监听器,一旦用户更改了日期选择器日期,我想立即工作,如下所示
已编辑
public class birthDate extends Activity{
DatePicker birthDayDatePicker,periodDatePicker;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.birthdate);
birthDayDatePicker = (DatePicker)findViewById(R.id.DatePickerBirthDay);
birthDayDatePicker.init(currentYear, currentMonth, currentDay, new OnDateChangedListener () {
@Override
public void onDateChanged(DatePicker birthDayDatePicker, int currentYear, int currentMonth, int currentDay) {
// TODO Auto-generated method stub
periodDateCalculations();
}
});
}
public void periodDateCalculations ()
{
Calendar start = Calendar.getInstance();
// get the chosen date from birth date picker
int birthYear = birthDayDatePicker.getYear();
int birthMonth = birthDayDatePicker.getMonth();
int birthDay = birthDayDatePicker.getDayOfMonth();
//set the chosen date to calendar instance
start.set(birthYear, birthMonth, birthDay);
//get the date
Date birthDate = start.getTime();
//int constrain = currentMonth + 9;
int daysToAdd = -280;
//another instance from calendar
Calendar cal2 = Calendar.getInstance();
//set birth date chosen to calendar
cal2.setTime(birthDate);
// if (cal.getTime().getMonth() >= constrain)
// {System.out.println("cal.getTime().getMonth() >= constrain");}
//add -280 day to birth day to get period date
cal2.add(Calendar.DAY_OF_MONTH,daysToAdd);
System.err.println("-----" +cal2.getTime());
int periodYearAfterCalc = cal2.getTime().getYear()+1900;
System.err.println("-----" + periodYearAfterCalc);
int periodMonthAfterCalc = cal2.getTime().getMonth();
System.err.println("----" + periodMonthAfterCalc);
int periodDayAfterCalc = cal2.getTime().getDate();
System.err.println(periodDayAfterCalc);
birthDayDatePicker.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
periodDatePicker.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
//edit birth date picker from user
if(birthDay >= currentDay && birthMonth >= currentMonth && birthYear >= currentYear){
//the program runs normally
periodDatePicker.updateDate(periodYearAfterCalc, periodMonthAfterCalc, periodDayAfterCalc);
}
else{
new AlertDialog.Builder(birthDate.this)
.setTitle("Wrong Data Input!")
.setMessage("birth day input error")
.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
periodDatePicker.updateDate(currentYear, currentMonth, currentDay);
}
}
我的问题是,这个监听器是否像它在 onCreate 中定义的那样工作不止一次,或者我应该在其他地方定义它以多次使用它?
提前致谢