How to use DatePickerDialog in Kotlin?

Adil Saiyad picture Adil Saiyad · Aug 23, 2017 · Viewed 47.5k times · Source

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?

Answer

Derek picture Derek · Aug 23, 2017

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.