I have implemented the date picker dialog on my activity and it works fine. When i click cancel the ate picker is dismissed so the buttons work. However i would like to capture the cancel button event and add more code to it to finish the activity but i cannot seem to be able to handle that. This is my code:
public class DatePickerActivity extends Activity {
static final int DATE_PICKER_ID = 1111;
private int year;
private int month;
private int day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date_picker);
// Get current date by calender
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
showDialog(DATE_PICKER_ID);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
// open datepicker dialog.
// set date picker for current date
// add pickerListener listner to date picker
return new DatePickerDialog(this, pickerListener, year, month,day);
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
@Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
Log.d("Date selected", String.valueOf(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" ")));
Intent intent = new Intent();
intent.putExtra("year", String.valueOf(new StringBuilder().append(year )));
intent.putExtra("month", String.valueOf(new StringBuilder().append(month + 1)));
intent.putExtra("day", String.valueOf(new StringBuilder().append(day)));
setResult(RESULT_OK, intent);
finish();
}
};
}
What i have tried is to add this onclick method like:
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(which==Dialog.BUTTON_NEGATIVE)
{
Log.i("dialog click", "dialog negative button clicked");
dialog.dismiss();
}
}
But this is not working. Any suggestions?
Make a class for DatePickerDialog and call it from
onCreate()
as follows:Call it from
onCreate()
You can try this code