DatePickerDialog无法进入onDateSet

时间:2017-05-02 06:16:56

标签: android

这是代码。我有一个Log.e来检查程序是否进入onDateSet函数,并发现它没有。

以下是代码:

private void datePicker(){
    //Calendar datePickercal = Calendar.getInstance();
    DatePickerDialog dialog = new DatePickerDialog(ContentInput.this, new DatePickerDialog.OnDateSetListener(){
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            Log.e(ErrorTag, "date picker: " + year + " " + month + " " + dayOfMonth);
            cal.set(year,month+1,dayOfMonth);
        }
    }
    ,cal.get(Calendar.YEAR)
    ,cal.get(Calendar.MONTH)
    ,cal.get(Calendar.DAY_OF_MONTH));

    dialog.show();
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, "ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            if (which == DialogInterface.BUTTON_POSITIVE) {
                timePicker();
            }
        }
    });
}

2 个答案:

答案 0 :(得分:2)

DatePickerDialog在正向按钮点击中调用其OnDateSetListener回调。实际上,DatePickerDialog通过调用setButton(BUTTON_POSITIVE, ...)来设置回调。您对该方法的调用将覆盖该方法,因此永远不会调用OnDateSetListener

timePicker()来电转移到onDateSet()方法,然后移除dialog.setButton()来电。

答案 1 :(得分:0)

这是日期选择器的代码

 calendar1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            dateflag = "from";
            DialogFragment newFragment = new SelectDateFragment();
            newFragment.show(getFragmentManager(), "DatePicker");

        }
    });


public static class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar calendar = Calendar.getInstance();
        int yy = calendar.get(Calendar.YEAR);
        int mm = calendar.get(Calendar.MONTH);
        int dd = calendar.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), this, 2017, 01, 01);
    }

    public void onDateSet(DatePicker view, int yy, int mm, int dd) {
        populateSetDate(yy, mm + 1, dd);
    }

    public void populateSetDate(int year, int month, int day) {
        if (dateflag.equals("from")) {
            from_date_ext.setText(day + "/" + month + "/" + year);
        } else {
            to_date_ext.setText(day + "/" + month + "/" + year);

        }
    }

}