我有一个活动,我已经覆盖了 optionsMenu。它有 3 个按钮,一个用于获取上一个列表,一个用于获取下一个列表,选项菜单上的第三个按钮应显示一个数据选择器,用户可以在其中选择他们想要查看的列表日期。如何将 DatePicker 侦听器附加到选项菜单中的“今天”按钮?
public void setCurrentDateOnView() {
dpResult = (DatePicker) findViewById(R.id.datepicker1);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into datepicker
// dpResult.init(year, month, day, null);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menurotadetails, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.previous:
DateTime now2 = nfcscannerapplication.getDate();
Log.e(TAG, "now2 = " + now2);
DateTime dateTimePlusOne2 = now2.minusDays(1);
Log.e(TAG, "now2 after -1 = " + dateTimePlusOne2);
nfcscannerapplication.setDate(dateTimePlusOne2);
DateTimeFormatter fmt2 = DateTimeFormat.forPattern("d-MMM-Y");
String nextDay2 = fmt2.print(dateTimePlusOne2);
Intent i2 = new Intent(this, NfcscannerActivity.class);
i2.putExtra("nextRota", nextDay2);
i2.setAction("NEXT_ROTA");
startActivity(i2);
return true;
case R.id.next:
DateTime now = nfcscannerapplication.getDate();
Log.e(TAG, "now = " + now);
DateTime dateTimePlusOne = now.plusDays(1);
Log.e(TAG, "now after +1 = " + dateTimePlusOne);
nfcscannerapplication.setDate(dateTimePlusOne);
DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y");
String nextDay = fmt.print(dateTimePlusOne);
Intent i = new Intent(this, NfcscannerActivity.class);
i.putExtra("nextRota", nextDay);
i.setAction("NEXT_ROTA");
startActivity(i);
return true;
case R.id.today:
setCurrentDateOnView();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void addListenerOnButton() {
??????.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
return new DatePickerDialog(this, datePickerListener, year, month,
day);
}
return null;
}
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) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// set selected date into datepicker also
dpResult.init(year, month, day, null);
}
};
. [更新]对不起,我没有想清楚,我只是做了以下
case R.id.today:
setCurrentDateOnView();
showDialog(DATE_DIALOG_ID);
return true;