datepicker-edittext只返回当前日期-怎么了?

7kqas0il  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(283)

主要活动

{
        date = findViewById(R.id.add_date);
        dueDate = findViewById(R.id.add_dueDate);
        final Calendar calendar = Calendar.getInstance();
        date.setOnClickListener(v -> {
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
            DatePickerDialog datePickerDialog = new DatePickerDialog(addScreen.this, (view, year, month, dayOfMonth) -> date.setText(SimpleDateFormat.getDateInstance().format(calendar.getTime())), year, month, day);
            datePickerDialog.show();
        });
        dueDate.setOnClickListener(v -> {
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
            DatePickerDialog datePickerDialog = new DatePickerDialog(addScreen.this, (view, year, month, dayOfMonth) -> dueDate.setText(SimpleDateFormat.getDateInstance().format(calendar.getTime())), year, month, day);
            datePickerDialog.show();
        });
    }

这个代码有点问题,我挑不出来。我得到日历(onclick提示符)来选择日期,但是即使我从过去、现在或将来选择日期,它总是在编辑文本中返回当前(今天)的日期。

gkl3eglg

gkl3eglg1#

您可以使用日历示例而不使用所选日期更新它,因此它包含当前日期。在使用日历示例之前,需要将所选日期设置为日历示例。

date.setOnClickListener(v -> {
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
            DatePickerDialog datePickerDialog = new DatePickerDialog(addScreen.this, { view, year, monthOfYear, dayOfMonth -> 
                calendar.set(Calendar.YEAR, year)
                calendar.set(Calendar.MONTH, monthOfYear)
                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)

                date.setText(SimpleDateFormat.getDateInstance().format(calendar.getTime()))

                }, year, month, day);
            datePickerDialog.show();
        });

相关:android datepicker

相关问题