当前位置: 首页 > 知识库问答 >
问题:

如何为Android5.0更改DatePicker对话框颜色

燕青青
2023-03-14

是否可以更改Android5.0的datepicker(以及timepicker)配色方案?

我尝试过设置重音颜色,但这都不起作用(使用android:):

<!-- colorPrimary is used for the default action bar background -->
<item name="colorPrimary">@color/purple</item>

<!-- colorPrimaryDark is used for the status bar -->
<item name="colorPrimaryDark">@color/purple_tint</item>

<!-- colorAccent is used as the default value for colorControlActivated
     which is used to tint widgets -->
<item name="colorAccent">@color/purple_tint</item>

共有1个答案

毋宸
2023-03-14

Neil的建议导致全屏datepicker的原因是父主题的选择:

<!-- Theme.AppCompat.Light is not a dialog theme -->
<style name="DialogTheme" parent="**Theme.AppCompat.Light**">
    <item name="colorAccent">@color/blue_500</item>
</style>

此外,如果采用此路由,则必须在创建DatePickerDialog时指定主题:

// R.style.DialogTheme
new DatePickerDialog(MainActivity.this, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        //DO SOMETHING
    }
}, 2015, 02, 26).show();

在我看来,这是不好的。应该尽量将样式设置在java之外,放在styles.xml/themes.xml内部。

重写应用程序基本主题中的DatePickerDialogTheme:

<style name="AppBaseTheme" parent="android:Theme.Material.Light">
    ....
    <item name="android:datePickerDialogTheme">@style/MyDatePickerDialogTheme</item>
</style>

定义MyDatePickerDialogTheme。父主题的选择取决于应用程序的基本主题:它可以是theme.Material.Dialogtheme.Material.Light.Dialog:

<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
    <item name="android:datePickerStyle">@style/MyDatePickerStyle</item>
</style>

我们已经使用样式MyDatePickerStyle重写了DatePickerStyle。父级的选择再次取决于应用程序的基本主题:widget.material.datepickerwidget.material.light.datepicker。根据您的要求定义它:

<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.Light.DatePicker">
    <item name="android:headerBackground">@color/chosen_header_bg_color</item>
</style>
dayOfWeekBackground
dayOfWeekTextAppearance
headerMonthTextAppearance
headerDayOfMonthTextAppearance
headerYearTextAppearance
headerSelectedTextColor
yearListItemTextAppearance
yearListSelectorColor
calendarTextColor
calendarSelectedTextColor

如果不想要这么多的控制(自定义),则不需要重写datepickerstyleColorAccent控制DatePicker的大部分颜色。因此,仅在MyDatePickerDialogTheme中重写ColorAccent就可以工作:

<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
    <item name="android:colorAccent">@color/date_picker_accent</item>

    <!-- No need to override 'datePickerStyle' -->
    <!-- <item name="android:datePickerStyle">@style/MyDatePickerStyle</item> -->
</style>

重写coloraccent还可以更改OKCancel文本颜色。还不错.

这样,您就不必向DatePickerDialog的构造函数提供任何样式信息。所有的东西都装好了:

DatePickerDialog dpd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

    }
 }, 2015, 5, 22);

 dpd.show();
 类似资料: