预定义日期显示在 android 中的日期选择器上

predefine date to display on datepicker in android

我试图让我的日期选择器显示我在单击它时设置的预定义日期。 我试过使用定界符分隔日期并根据年月日设置它们,但它仍然不起作用。它一直显示当前日期而不是我设置的日期

val date = '03-22-2022'
 val startCalendar = Calendar.getInstance()

        val startPicker = DatePickerDialog.OnDateSetListener{ view, year, month, dayOfMonth ->
            startCalendar.set(Calendar.YEAR,year)
            startCalendar.set(Calendar.MONTH,month)
            startCalendar.set(Calendar.DAY_OF_MONTH,dayOfMonth)
            
        }

        editstartdatepicker.setOnClickListener{
            val dialog = DatePickerDialog(this,
                startPicker,
                startCalendar.get(Calendar.YEAR),
                startCalendar.get(Calendar.MONTH),
                startCalendar.get(Calendar.DAY_OF_MONTH))
            dialog.show()

        }

有帮助吗

  DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
datePicker.updateDate(2016, 5, 22);

您应该初始化 startCalender,因为它指向当前日期 使用这个

    val date = "03-22-2022"
    val startCalendar = Calendar.getInstance()

    val sdf = SimpleDateFormat("MM-dd-yyyy", Locale.ENGLISH)
    startCalendar.time = sdf.parse(date)