【问题标题】:DatePicker - EditText only returning current date - what's wrong?DatePicker - EditText 只返回当前日期 - 怎么了?
【发布时间】:2020-11-18 09:15:36
【问题描述】:

主要活动

 {
        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 提示)选择日期,但即使我选择过去、现在或未来的日期,它总是在编辑文本中返回当前(今天的)日期。

【问题讨论】:

    标签: java android android-studio date kotlin


    【解决方案1】:

    您在使用日历实例时未使用所选日期对其进行更新,因此它包含当前日期。您需要在使用之前将所选日期设置为日历实例。

    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

    【讨论】:

    • 它说“预期 1 个参数,但找到 2 个”
    • //日历提示日期 date = findViewById(R.id.add_date); dueDate = findViewById(R.id.add_dueDate);最终日历日历 = Calendar.getInstance(); date.setOnClickListener(v -> { year = calendar.get(Calendar.YEAR, year); month = calendar.get(Calendar.MONTH, month); day = calendar.get(Calendar.DAY_OF_MONTH, day); });
    • 你能帮我解决这个问题吗? stackoverflow.com/questions/64888676/…
    猜你喜欢
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 2014-06-05
    • 1970-01-01
    • 2016-01-09
    相关资源
    最近更新 更多