我正在使用这个Android应用程序,用户点击选择日期按钮并弹出日期选择器对话框,用户可以设置日期并按对话框的设置按钮。我无法在设置按钮后面获得事件监听器。我希望用户在该设置按钮后面的对话框中设置日期。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_locations);
pickBtn = (Button) findViewById(R.id.pickDateButton);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
month = month + 1;
pickBtn.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("deprecation")
@Override
public void onClick(View v) {
showDialog(DATE_PICKER_ID);
}
});
}
private 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) {
Toast.makeText(getApplicationContext(),"fdf",
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Tracking Stopped",
Toast.LENGTH_LONG).show();
year = selectedYear;
month = selectedMonth;
day = selectedDay;
}
};
我有没有写过合适的听众?它不会在侦听器中显示toast消息,因此当用户按下set按钮并关闭对话框时,它不会进入其中。
答案 0 :(得分:1)
是的,您的听众是正确的,但您没有设置对话的监听器。所以我建议你覆盖onCreateDialog方法。像上面的代码一样:
@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;
}
这样你的活动就会听你刚刚创建的DatePickerDialog实例中的变化。
因为不推荐使用showDialog(DATE_PICKER_ID)和onCreateDialog(int id)。我建议您在不使用这些方法的情况下创建自己的DatePickerDialog实例。像
pickBtn.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("deprecation")
@Override
public void onClick(View v) {
new DatePickerDialog(this, pickerListener, year, month,day);
}
});
答案 1 :(得分:0)
在大多数情况下,你做得对,但尝试这样做。
static final int DATE_PICKER_ID= 999;
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
return new DatePickerDialog(this, datePickerListener , year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// onDateSet method
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//your code here
}
};