Search code examples
androiddatepickertimepicker

How to change the style from DatePicker and TimePicker programmatically in Android?


I created a TabHost which contains 2 tabs with a DatePicker and a TimePicker:

TabHost dayTabHost = (TabHost) layout.findViewById(R.id.tabHost);
dayTabHost.setup();

TabHost.TabSpec dayTabSpec = dayTabHost.newTabSpec("Day");
dayTabSpec.setIndicator("Day");
dayTabSpec.setContent(new TabHost.TabContentFactory() {
                public View createTabContent(String arg) {
                    DatePicker datePicker = new DatePicker(getBaseContext());
                    return datePicker;
                }
            });
dayTabHost.addTab(dayTabSpec);

TabHost.TabSpec timeTabSpec= dayTabHost.newTabSpec("Time");
timeTabSpec.setIndicator("Time");
timeTabSpec.setContent(new TabHost.TabContentFactory() {
                public View createTabContent(String arg) {
                    TimePicker timePicker = new TimePicker(getBaseContext());
                    return timePicker;
                }
            });
dayTabHost.addTab(timeTabSpec);

I don't know how to change the color of those Pickers to a different style that is used in the app in this situation.


Solution

  • I've found my own answer and it is quite simple. When instaciating the TimePicker and DatePicker send as parameter a new ContextThemeWrapper with the custom style you want in order to change the style.

    Style.xml

    <style name="CustomPickerTheme">
        <item name="colorAccent">@color/Red</item>
    </style>
    

    MainActivity.class

    TimePicker timePicker = new TimePicker(new ContextThemeWrapper(MainActivity.this, R.style.CustomPickerTheme));
    DatePicker datePicker = new DatePicker(new ContextThemeWrapper(MainActivity.this, R.style.CustomPickerTheme));