今天在看需求的时候,看到了选择时间的功能,然后我第一反应就想到了TimePickerView时间选择器,大佬封装的简直完美,大部分需求都是可以满足的,但是还有一些比较坑的需求,比如分钟只显示以10为单位的,我看了大佬的代码,没有找到,好像似乎没有这个功能,本来想着看能不能改下源码加下,真是人算不如天算,这个需求不要了!!!太好了……
首先贴出大佬的github
https://github.com/Bigkoo/Android-PickerView
一、使用TimePickerView
接下来就是我的使用,以及两个时间之间的简单运算了,
首先我们需要导入依赖,
compile 'com.contrarywind:Android-PickerView:3.2.7'
你可以选择使用最新的版本,我的这个并不是最新的。
如果需要改源码的话,那就只能下载大佬的demo,然后导入module了。
然后我们同步一下就行了。
使用起来也是非常的简单
TimePickerView timePickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date, View v) {
String start = getTime(date);
startDate.setText(start);
}
}).setType(new boolean[]{true, true, true, true, true, false})
.setCancelColor(getResources().getColor(R.color.c1))
.setSubmitColor(getResources().getColor(R.color.c1)).build();
//注:根据需求来决定是否使用该方法(一般是精确到秒的情况),此项可以在弹出选择器的时候重新设置当前时间,避免在初始化之后由于时间已经设定,导致选中时间与当前时间不匹配的问题。
timePickerView.setDate(Calendar.getInstance());
timePickerView.show();
这里需要注意的就是getTime这个方法,
private String getTime(Date date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
return format.format(date);
}
这个方法是根据自己项目的需求来定的,比如说你只需要年月日yyyy-MM-dd,就只需要这个就行,
这个就是简单的使用,怎么样,简单吧,当然还有一些自定义的属性:
.setType(new boolean[]{true, true, true, true, true, true})// 默认全部显示
.setCancelText("Cancel")//取消按钮文字
.setSubmitText("Sure")//确认按钮文字
.setContentSize(18)//滚轮文字大小
.setTitleSize(20)//标题文字大小
.setTitleText("Title")//标题文字
.setOutSideCancelable(false)//点击屏幕,点在控件外部范围时,是否取消显示
.isCyclic(true)//是否循环滚动
.setTitleColor(Color.BLACK)//标题文字颜色
.setSubmitColor(Color.BLUE)//确定按钮文字颜色
.setCancelColor(Color.BLUE)//取消按钮文字颜色
.setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
.setBgColor(0xFF333333)//滚轮背景颜色 Night mode
.setDate(selectedDate)// 如果不设置的话,默认是系统时间*/
.setRangDate(startDate,endDate)//起始终止年月日设定
.setLabel("年","月","日","时","分","秒")//默认设置为年月日时分秒
.isCenterLabel(false) //是否只显示中间选中项的label文字,false则每项item全部都带有label。
.isDialog(true)//是否显示为对话框样式
这里注意的就是new boolean[]{true, true, true, true, true, true}这个,就是控制年月日时分秒的,不要那个就false就行了,
好了,这样就算真的完了,就可以正常使用了。
二、两个时间的简单运算
1、获取当前的时间:
public static String getNowTime() {
String timeString = null;
Time time = new Time();
time.setToNow();
String year = thanTen(time.year);
String month = thanTen(time.month + 1);
String monthDay = thanTen(time.monthDay);
String hour = thanTen(time.hour);
String minute = thanTen(time.minute);