如何在Android中以编程方式更改DatePicker和TimePicker的样式?

时间:2017-01-18 16:03:32

标签: android datepicker timepicker

我创建了一个TabHost,其中包含2个带有DatePicker和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);

我不知道如何将这些选择器的颜色更改为在这种情况下在应用程序中使用的不同样式。

1 个答案:

答案 0 :(得分:4)

我找到了自己的答案,这很简单。当实例化TimePicker和DatePicker时,将一个新的ContextThemeWrapper作为参数发送,并使用您想要的自定义样式来更改样式。

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