我想显示日期选择器弹出窗口。我找到了一些例子,但我没有正确理解。我有一个按钮,我希望当我单击按钮时会弹出日期选择器对话框,并且在设置日期后,日期应该存储在一个变量中。请提供示例代码或良好的链接。
问问题
47270 次
2 回答
36
尝试这个。
在您的按钮单击中使用此代码。将显示日期选择器对话框。
Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
System.out.println("the selected " + mDay);
DatePickerDialog dialog = new DatePickerDialog(Registration.this,
new mDateSetListener(), mYear, mMonth, mDay);
dialog.show();
然后,mDateSetListener
需要编写类。
class mDateSetListener implements DatePickerDialog.OnDateSetListener {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
// getCalender();
int mYear = year;
int mMonth = monthOfYear;
int mDay = dayOfMonth;
v.setText(new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("/").append(mDay).append("/")
.append(mYear).append(" "));
System.out.println(v.getText().toString());
}
}
请检查此答案并投票。
于 2013-09-25T05:29:04.163 回答
13
使此类成为您活动中的内部类
如果您想将当前日期设置为打开 datePicker 时看到的日期。你可以像这样得到它
Calendar c = Calendar.getInstance();
int startYear = c.get(Calendar.YEAR);
int startMonth = c.get(Calendar.MONTH);
int startDay = c.get(Calendar.DAY_OF_MONTH);
class StartDatePicker extends DialogFragment implements DatePickerDialog.OnDateSetListener{
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
// Use the current date as the default date in the picker
DatePickerDialog dialog = new DatePickerDialog(BookingFormActivity.this, this, startYear, startMonth, startDay);
return dialog;
}
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
// Do something with the date chosen by the user
startYear = year;
startMonth = monthOfYear;
startDay = dayOfMonth;
updateStartDateDisplay();
}
}
您可以通过将此方法设置为 onClick 来调用此对话框
public void showStartDateDialog(View v){
DialogFragment dialogFragment = new StartDatePicker();
dialogFragment.show(getFragmentManager(), "start_date_picker");
}
于 2013-09-25T05:25:26.287 回答