Search code examples
androidkotlindatepicker

Set custom color on a Datepicker Dialog in Kotlin


So, total begginner here and im trying to do a datepicker dialog in android studio. Everything works fine but i have no idea how to change the color of the dialog.

My code looks like this

 val datePicker = DatePickerDialog.OnDateSetListener { view, years, month, dayOfMonth ->

            myCalendar.set(Calendar.YEAR, years)
            myCalendar.set(Calendar.MONTH, month)
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)

            updateLable(myCalendar)
        }

        btnDatePicker.setOnClickListener{
            DatePickerDialog(this, datePicker, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show()
        }

can someone help me with this ?

I tried looking for a solution online but it's always in older version of android or the code straight up doesn't work :/


Solution

  • your .xml file

    <style name="CustomDatePickerDialog" parent="Theme.AppCompat.Light.Dialog">
        <!-- Customize these colors according to your needs -->
        <item name="colorAccent">#FF4081</item>
        <item name="android:textColorPrimary">#FFFFFF</item>
        <item name="android:textColorSecondary">#BDBDBD</item>
        <item name="android:background">#3F51B5</item>
    </style>
    

    update the code your provided

    val datePicker = DatePickerDialog.OnDateSetListener { view, years, month, dayOfMonth ->
        myCalendar.set(Calendar.YEAR, years)
        myCalendar.set(Calendar.MONTH, month)
        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
        updateLabel(myCalendar)
    }
    
    btnDatePicker.setOnClickListener {
        DatePickerDialog(
            this, 
            R.style.CustomDatePickerDialog, // Apply the custom style here
            datePicker, 
            myCalendar.get(Calendar.YEAR), 
            myCalendar.get(Calendar.MONTH), 
            myCalendar.get(Calendar.DAY_OF_MONTH)
        ).show()
    }
    

    DatePickerDialog should reflect the custom colors you defined in the CustomDatePickerDialog style

    If needed update your AndroidManifest.xml ading AppCompat theme.

    <application
        android:theme="@style/Theme.AppCompat.Light">
    </application>