代码之家  ›  专栏  ›  技术社区  ›  Azyoko

在Kotlin的日期选择器对话框上设置自定义颜色

  •  0
  • Azyoko  · 技术社区  · 1 年前

    所以,总的来说,我在这里开始尝试在android工作室中进行日期选择对话框。一切都很好,但我不知道如何更改对话框的颜色。

    我的代码如下

     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()
            }
    

    有人能帮我做这个吗?

    我试着在网上寻找解决方案,但它总是在旧版本的android中,或者代码直接不起作用:/

    1 回复  |  直到 1 年前
        1
  •  0
  •   TourEiffel    1 年前

    您的.xml文件

    <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>
    

    更新您提供的代码

    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 应该反映您在中定义的自定义颜色 CustomDatePickerDialog 风格

    如果需要,请更新您的 AndroidManifest.xml 正在加载 AppCompat 主题

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