我是android开发的新手,我正在尝试开发一个年龄计算器。使用我当前的代码,我能够正确找到年份和月份之间的差异,但日期不正确。我知道我做错了什么。但我无法弄清楚。我也使用了 jodatime api,但是当我使用它时,当我调用这个函数时我的应用程序关闭了,我无法理解我做错了什么。我的代码是:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDateDisplay = (TextView) findViewById(R.id.showMyDate);
mPickDate = (Button) findViewById(R.id.myDatePickerButton);
mPickDate.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("deprecation")
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
dob_Year = c.get(Calendar.YEAR);
dob_Month = c.get(Calendar.MONTH);
dob_Day = c.get(Calendar.DAY_OF_MONTH);
// display the current date
updateDisplay();
}
private void updateAge()
{
current_Year = c.get(Calendar.YEAR);
current_Month = c.get(Calendar.MONTH);
current_Day = c.get(Calendar.DAY_OF_YEAR);
if (current_Day < dob_Day) {
current_Month--;
current_Day+=c.getMaximum(dob_Month);
}
if (current_Month < dob_Month) {
current_Year--;
current_Month += 12;
}
int ageYear=current_Year-dob_Year;
int ageMonths=current_Month-dob_Month;
int ageDays= current_Day-dob_Day;
this.mAgeDisplay.setText(
new StringBuilder()
.append(ageYear).append(" Years ")
.append(ageMonths).append(" Months ")
.append(ageDays).append(" Days "));
}
private void updateDisplay() {
this.mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(dob_Day).append("-")
.append(dob_Month + 1).append("-")
.append(dob_Year).append(" "));
}
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
dob_Year = year;
dob_Month = monthOfYear;
dob_Day = dayOfMonth;
updateDisplay();
updateAge();
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
dob_Year, dob_Month, dob_Day);
}
return null;
}
在此代码片段中,dob_ 变量从 datepicker 获取它们的值。