1.Android设置TimePicker样式和字体颜色
Android默认的TimePicker有两种,6.0为Dialog样式,6.0之前为Spinner样式
设置TimePicker选择器风格
一种是
android:timePickerMode="clock"
image.png
另一种是
android:timePickerMode="spinner"
[图片上传中...(image.png-7ac7c0-1593766325814-0)]
image.png
TimePicker的显示规模大小设置
数字越大 显示越大
android:scaleX="2"
android:scaleY="2"
TimePicker的数据回调
mTimepicker = (TimePicker) inflate.findViewById(R.id.timepicker);
mTimepicker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS); //设置点击事件不弹键盘
mTimepicker.setIs24HourView(true); //设置时间显示为24小时
mTimepicker.setHour(8); //设置当前小时
mTimepicker.setMinute(10); //设置当前分(0-59)
mTimepicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { //获取当前选择的时间
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
}
});
利用反射修改一些选择器的字体效果与背景颜色
需要用到反射的方法了,比如更改分割线的样式,设置起始截止时间等:
首先我们要通过反射获取TimePicker源码里hour和minute的id:
Resources systemResources = Resources.getSystem();
int hourNumberPickerId = systemResources.getIdentifier("hour", "id", "android");
int minuteNumberPickerId = systemResources.getIdentifier("minute", "id", "android");
然后用我们定义的TimePicker来获取这个id并转换成hour和minute对应的NumberPicker:
NumberPicker hourNumberPicker = (NumberPicker) mTimepicker.findViewById(hourNumberPickerId);
NumberPicker minuteNumberPicker = (NumberPicker) mTimepicker.findViewById(minuteNumberPickerId);
通过获取到的hourNumberPicker和minuteNumberPicker我们可以先进行TimePicker的时间限制:
hourNumberPicker.setMinValue(8); //设置最小hour
hourNumberPicker.setMaxValue(12); //设置最大hour
minuteNumberPicker .setMinValue(0); //设置最小minute
minuteNumberPicker .setMaxValue(30); //设置最大minute
修改滚动条背景颜色
hourNumberPicker.setBackgroundColor(getResources().getColor(R.color.colorBlue));// 修改背景颜色
image.png
隐藏冒号
用最暴力的方式隐藏滚动条的冒号,就是直接找ChildAt
ViewGroup view = (ViewGroup) mTimepicker.getChildAt(0);
ViewGroup view2 = (ViewGroup) view.getChildAt(1);
view2.getChildAt(1).setVisibility(View.GONE);
禁止键盘输入
mTimePicker.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
TimePicker分割线的颜色和高度
private void setNumberPickerDivider(NumberPicker numberPicker) {
NumberPicker picker = numberPicker;
Field[] pickerFields = NumberPicker.class.getDeclaredFields();
for (Field pf : pickerFields) {
if (pf.getName().equals("mSelectionDivider")) { //设置颜色
pf.setAccessible(true);
ColorDrawable colorDrawable = new ColorDrawable(
ContextCompat.getColor(this, R.color.colortime)); //选择自己喜欢的颜色
try {
pf.set(numberPicker, colorDrawable);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
if (pf.getName().equals("mSelectionDividerHeight")) { //设置高度
pf.setAccessible(true);
try {
int result = 3; //要设置的高度
pf.set(picker, result);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
picker.invalidate();
}
}
网友评论