Datepicker:如何在单击按钮时弹出datepicker并将值存储在变量中

时间:2013-09-25 05:17:44

标签: android datepicker android-datepicker

我想显示datepicker弹出窗口。我找到了一些例子,但我没有得到正确的答案。我有一个按钮,我希望当我点击按钮时,应弹出datepicker对话框,并在设置日期后,日期应存储在变量中。 PLease为我提供了示例代码或良好的链接。

2 个答案:

答案 0 :(得分: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());


        }
    }

请检查此答案并投票。

答案 1 :(得分: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");
    }