从源码看,DatePicker和TimePicker都是一个FrameLayout,有两种布局,一种是Material Design的时钟样式,一种是下图的Spinner样式,如图(DatePicker):
在xml文件中(date_picker_legacy、time_picker_legacy)可以看到DatePicker和TimePicker是多个NumberPicker构成的,Spinner中间都是蓝色的分割线,但并没有提供方法可以进行颜色的修改,因此可以考虑使用反射的方法来修改分割线颜色。下面通过TimePicker为例说明一下修改流程:
1. 获取系统资源,拿到TimePicker中的NumberPicker资源id:
Resources systemResources = Resources.getSystem();
int hourNumberPickerId = systemResources.getIdentifier("hour", "id", "android");
int minuteNumberPickerId = systemResources.getIdentifier("minute", "id", "android");
注意:这里如果是DatePicker,则hour、minute改为month、day、year
2. 通过资源id找到TimePicker中的NumberPicker:
NumberPicker hourNumberPicker = (NumberPicker) timePicker.findViewById(hourNumberPickerId);
NumberPicker minuteNumberPicker = (NumberPicker) timePicker.findViewById(minuteNumberPickerId);
3. 利用反射修改NumberPicker中的颜色,分割线颜色是由NumberPicker中的变量mSelectionDivider保存的
private void setNumberPickerDivider(NumberPicker numberPicker) {
final int count = numberPicker.getChildCount();
for(int i = 0; i < count; i++){
try{
Field dividerField = numberPicker.getClass().getDeclaredField("mSelectionDivider");
dividerField.setAccessible(true);
ColorDrawable colorDrawable = new ColorDrawable(
ContextCompat.getColor(this, android.R.color.holo_red_light));
dividerField.set(numberPicker,colorDrawable);
numberPicker.invalidate();
}
catch(NoSuchFieldException | IllegalAccessException | IllegalArgumentException e){
Log.w("setNumberPickerTxtClr", e);
}
}
}
调用上面方法,将获得的numberPicker作为参数传入即可。