这可能会帮助您:
public class TestActivity extends Activity {
private int mYear;
private int mMonth;
private int mDay;
private void showDialog() {
if (mYear == 0 || mMonth == 0 || mDay == 0) {
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
}
DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
editText.setText(selectedYear + "年" + selectedMonth + 1 + "月"
+ selectedDay + "日");
mYear = selectedYear;
mMonth = selectedMonth;
mDay = selectedDay;
}
};
DatePickerDialog datePickerDialog = new DatePickerDialog(
SampleActivity.this, datePickerListener, mYear, mMonth, mDay);
datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
dialog.cancel();
}
}
});
datePickerDialog.setCancelable(false);
datePickerDialog.show();
}
}
下面的示例代码将给出完整的解决方案:
public class SecondActivity extends FragmentActivity implements OnClickListener{
private static final String TAG = SecondActivity.class.getName();
private int year;
private int month;
private int day;
private boolean isCancelled;
private EditText editText;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.second_activity_layout);
editText = (EditText) findViewById(R.id.editText);
}
public void onButtonClick(View view) {
onClick(view);
}
@Override
public void onClick(View v) {
if(year == 0) {
Calendar calendar = Calendar.getInstance();
day = calendar.get(Calendar.DAY_OF_MONTH);
month = calendar.get(Calendar.MONTH);
year = calendar.get(Calendar.YEAR);
}
OnDateSetListener callBack = new OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
if(isCancelled) {
Log.i(TAG, "Cancelled");
isCancelled = false;
} else {
editText.setText("Date selected");
month = monthOfYear;
day = dayOfMonth;
SecondActivity.this.year = year;
}
}
};
DatePickerDialog dialog = new DatePickerDialog(this, callBack, year, month, day);
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == DialogInterface.BUTTON_NEGATIVE) {
Log.i(TAG, "Cancel");
isCancelled = true;
dialog.dismiss();}
}
});
dialog.setCancelable(false);
dialog.show();
}
}