Search code examples
kotlindatepickerdialog

How to use DatePickerDialog in Kotlin?


In Java an DatePickerDialog can be use such as:

final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);


DatePickerDialog dpd = new DatePickerDialog(getActivity(),new DatePickerDialog.OnDateSetListener()
{
   @Override
   public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
  {
      // Display Selected date in textbox
      lblDate.setText(""+ dayOfMonth+" "+MONTHS[monthOfYear] + ", " + year);
  }
}, year, month,day);
dpd.show();

How does Kotlin's DatePickerDialog use look like?


Solution

  • It would look something like this:

    val c = Calendar.getInstance()
    val year = c.get(Calendar.YEAR)
    val month = c.get(Calendar.MONTH)
    val day = c.get(Calendar.DAY_OF_MONTH)
    
    
    val dpd = DatePickerDialog(activity, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
    
        // Display Selected date in textbox
        lblDate.setText("" + dayOfMonth + " " + MONTHS[monthOfYear] + ", " + year)
    
    }, year, month, day)
    
    dpd.show()
    

    this was done by simply copying and pasting the code into a kotlin file in android studio. I would strongly recommend using it.