我已经在活动中实现了日期选择器对话框,并且工作正常。当我单击“取消”时,会关闭“进餐选择器”,因此按钮会起作用。但是,我想捕获取消按钮事件并向其添加更多代码以完成活动,但我似乎无法处理该事件。这是我的代码:
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();
}
};
}
我尝试过的是添加如下onclick方法:
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();
}
}
但这是行不通的。有什么建议?
您可以尝试此代码
@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
DatePickerDialog dialog = new DatePickerDialog(this, pickerListener, year, month,day);
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Text", new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
// Do Stuff
Log.i("dialog click", "dialog negative button clicked");
dialog.dismiss();
}
}
});
return dialog;
}
return null;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句