Android 中NumberPicker,DatePicker与DatePickerDialog中分割颜色的修改实例代码
Android 中NumberPicker,DatePicker与DatePickerDialog中分割颜色的修改实例代码
前言: 开发中,为了应用整体美观,需要保持控件的色调和主题色保持一致,
例如:NumberPicker、DatePicker和DatePickerDialog的分割线颜色
一、NumberPicker的分割线颜色
我把对NumberPicker分割线颜色的方法写在一个工具类中,便于全局调用,代码如下:
public static void setNumberPickerDividerColor(Context context, NumberPicker numberPicker) { NumberPicker picker = numberPicker; Field[] pickerFields = NumberPicker.class.getDeclaredFields(); for (Field pf : pickerFields) { if (pf.getName().equals("mSelectionDivider")) { pf.setAccessible(true); try { //设置分割线的颜色值 pf.set(picker, new ColorDrawable(context.getResources().getColor(R.color.theme_pink))); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (Resources.NotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } break; } } }
二、DatePicker的分割线颜色
查看DataPicker的源码可以看到,DatePacker也是NumberPicker实现的,所以主要思想,还是修改NumberPicker分割线的颜色,代码如下:
public static void setDatePickerDividerColor(Context context, DatePicker datePicker){ // 获取 mSpinners LinearLayout llFirst = (LinearLayout) datePicker.getChildAt(0); // 获取 NumberPicker LinearLayout mSpinners = (LinearLayout) llFirst.getChildAt(0); for (int i = 0; i < mSpinners.getChildCount(); i++) { NumberPicker picker = (NumberPicker) mSpinners.getChildAt(i); Field[] pickerFields = NumberPicker.class.getDeclaredFields(); for (Field pf : pickerFields) { if (pf.getName().equals("mSelectionDivider")) { pf.setAccessible(true); try { pf.set(picker, new ColorDrawable(context.getResources().getColor(R.color.theme_pink))); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (Resources.NotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } break; } } } }
二、DatePickerDialog的分割线颜色
实现思路:拿到Dialog中DatePicker就可以改变分割先的颜色,主要代码如下:
DatePickerDialog datePickerDialog = new DatePickerDialog(mContext, 0, listener, year, month, day); datePickerDialog.setTitle("选择年月"); datePickerDialog.show(); DatePicker datePicker = datePickerDialog.getDatePickerStart(); //获取DatePicker CommonUtil.setDatePickerDividerColor(mContext, datePicker); //设置分割线颜色 /*修改按钮颜色这个必须在show或者create方法后面*/ Button commitBtn = datePickerDialog.getButton(DialogInterface.BUTTON_POSITIVE); //确认按钮 commitBtn.setTextColor(Color.parseColor("#e8615e"));
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
赞 (0)