TimePickerDialog 时间日期选择器,以及继承重写后修改分钟的间隔

 重写类,实现分钟间隔

/**
 * 自定义时间选择器,重写了TimePickerDialog,让分钟的滚动条间隔10个一跳动
 * Created by IKL on 2019/4/29.
 */

public class CustomTimePickerDialog extends TimePickerDialog
{
    final OnTimeSetListener mCallback;
    TimePicker mTimePicker;
    final int increment;//调整跳过的滚动距离,10的话就是每十个一显示
//    private String[] name=new String[]{"00","10","20","30","40","50"};
private String[] name;//与间隔对应的数据
    public CustomTimePickerDialog(Context context, int themeResId, OnTimeSetListener callBack,
                                  int hourOfDay, int minute, boolean is24HourView,int interval, String[] name)
    {

        super(context,themeResId, callBack, hourOfDay, minute, is24HourView);

        this.mCallback = callBack;
        this.increment = interval;
        this.name=name;
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (mCallback != null && mTimePicker!=null) {
            mTimePicker.clearFocus();
            mCallback.onTimeSet(mTimePicker, mTimePicker.getCurrentHour(),
                    mTimePicker.getCurrentMinute()*increment);
        }
    }

    @Override
    protected void onStop()
    {
        // override and do nothing
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        try
        {
            Class<?> rClass = Class.forName("com.android.internal.R$id");
            Field timePicker = rClass.getField("timePicker");
            this.mTimePicker = (TimePicker)findViewById(timePicker.getInt(null));
            Field m = rClass.getField("minute");

            NumberPicker mMinuteSpinner = (NumberPicker)mTimePicker.findViewById(m.getInt(null));
            mMinuteSpinner.setMinValue(0);
            mMinuteSpinner.setMaxValue((60/increment)-1);//显示计算

            List<String> displayedValues = new ArrayList<String>();
            for(int i=0;i<60;i+=increment)//循环,处理的是关于返回值,必须要与你自己需要间隔的对等
            {
                displayedValues.add(String.format("%02d", i));
            }
            mMinuteSpinner.setDisplayedValues(name);


        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

工具类,里面包含了上面那个自定义的时间选择类调用方法

/**
 * 时间选择器工具类
 * Created by IKL on 2019/4/8.
 */

public class BasisTimesUtils {
    public static int THEME_DEVICE_DEFAULT_LIGHT = AlertDialog.THEME_DEVICE_DEFAULT_LIGHT;
    public static int THEME_DEVICE_DEFAULT_DARK = AlertDialog.THEME_DEVICE_DEFAULT_DARK;
    public static int THEME_TRADITIONAL = AlertDialog.THEME_TRADITIONAL;
    public static int THEME_HOLO_LIGHT = AlertDialog.THEME_HOLO_LIGHT;
    public static int THEME_HOLO_DARK = AlertDialog.THEME_HOLO_DARK;
    private static DatePickerDialog mDatePickerDialog;//日期选择器

    /**
     * 将字符串时间转为Long时间
     *
     * @param time yyyy-MM-dd HH:mm:ss:SSS
     */
    public static Long getLongTimeOfSSS(String time) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            Date date = sdf.parse(time);
            return date.getTime();
        } catch (Exception e) {
        }
        return 0L;
    }

    /**
     * 将字符串时间转为Long时间
     *
     * @param time yyyy-MM-dd HH:mm:ss
     */
    public static Long getLongTime(String time) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = sdf.parse(time);
            return date.getTime();
        } catch (Exception e) {
        }
        return 0L;
    }

    /**
     * 将字符串时间转为Long时间
     *
     * @param time yyyy-MM-dd
     */
    public static Long getLongTimeOfYMD(String time) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(time);
            return date.getTime();
        } catch (Exception e) {
        }
        return 0L;
    }

    /**
     * 将Long时间转成String时间
     *
     * @return yyyy-MM-dd HH:mm:ss:SSS
     */
    public static String getStringTimeOfSSS(Long time) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        return sdf.format(date);
    }

    /**
     * 将Long时间转成String时间
     *
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getStringTime(Long time) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * 将Long时间转成String时间
     *
     * @return yyyy-MM-dd
     */
    public static String getStringTimeOfYMD(Long time) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    /**
     * 当前的时间(设备)
     *
     * @return yyyy-MM-dd HH:mm:ss:SSS
     */
    public static String getDeviceTimeOfSSS() {
        String date = "";
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            date = df.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
            date = new Date().getTime() + "";//当前时间的long字符串
        }
        return date;
    }

    /**
     * 当前的时间(设备)
     *
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getDeviceTime() {
        String date = "";
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            date = df.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
            date = new Date().getTime() + "";//当前时间的long字符串
        }
        return date;
    }

    /**
     * 当前的时间(年月日)
     *
     * @return yyyy-MM-dd
     */
    public static String getDeviceTimeOfYMD() {
        String date = "";
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            date = df.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 当前的时间(年月)
     *
     * @return yyyy-MM
     */
    public static String getDeviceTimeOfYM() {
        String date = "";
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
            date = df.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 获取某月最后一天(年月日)
     *
     * @return yyyy-MM
     */
    public static String getLastDayOfMonthOfYMD(int year, int month) {
        Calendar cal = Calendar.getInstance();
        // 设置年份
        cal.set(Calendar.YEAR, year);
        // 设置月份
        cal.set(Calendar.MONTH, month - 1);
        // 获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        // 设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());

        return lastDayOfMonth;
    }

    /**
     * 获取某月最后一天(日)
     */
    public static int getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        // 设置年份
        cal.set(Calendar.YEAR, year);
        // 设置月份
        cal.set(Calendar.MONTH, month - 1);
        // 获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

        return lastDay;
    }

    /**
     * 显示日期选择器
     *
     * @param themeLight true 白色背景; false 黑色背景
     */
    public static BasisTimesUtils showDatePickerDialog(Context context, boolean themeLight, String title
            , int year, int month, int day, OnDatePickerListener onDateTimePickerListener) {
        int themeId = AlertDialog.THEME_HOLO_LIGHT;//默认白色背景
        if (!themeLight) {
            themeId = AlertDialog.THEME_HOLO_DARK;//黑色背景
        }
        return showDatePickerDialog(context, themeId, title, year, month, day, onDateTimePickerListener);
    }

    /**
     * 显示日期选择器, 默认白色背景
     */
    public static BasisTimesUtils showDatePickerDialog(Context context, String title, int year, int month,
      int day, OnDatePickerListener onDateTimePickerListener) {
        return showDatePickerDialog(context, AlertDialog.THEME_HOLO_LIGHT, title, year, month, day, onDateTimePickerListener);
    }

    /**
     * 显示日期选择器  年月日
     */
    public static BasisTimesUtils showDatePickerDialog(Context context, int themeId, String title,
                                                       int year, int month, int day,
                                                       final OnDatePickerListener onDateTimePickerListener) {
        mDatePickerDialog = new DatePickerDialog(context, themeId, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                month = month + 1;//月份加一
                if (onDateTimePickerListener != null) {
                    onDateTimePickerListener.onConfirm(year, month, dayOfMonth);
                }
            }

        }, year, month - 1, day);//月份减一
        mDatePickerDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (onDateTimePickerListener != null) {
                    onDateTimePickerListener.onCancel();
                }
            }
        });

        if (!TextUtils.isEmpty(title)) {
            mDatePickerDialog.setTitle(title);
        }
        mDatePickerDialog.show();
        return new BasisTimesUtils();
    }

    /**
     * 隐藏年, 只显示月和日
     */
    public void setYearGone() {
        setSpecialDatePicker(1);
    }

    /**
     * 隐藏日, 只显示年和月
     */
    public void setDayGone() {
        setSpecialDatePicker(2);
    }

    private void setSpecialDatePicker(int state) {
        try {
            DatePicker dp = mDatePickerDialog.getDatePicker();

            NumberPicker view0 = (NumberPicker) ((ViewGroup) ((ViewGroup) dp.getChildAt(0)).getChildAt(0)).getChildAt(0); //获取最前一位的宽度
            NumberPicker view1 = (NumberPicker) ((ViewGroup) ((ViewGroup) dp.getChildAt(0)).getChildAt(0)).getChildAt(1); //获取中间一位的宽度
            NumberPicker view2 = (NumberPicker) ((ViewGroup) ((ViewGroup) dp.getChildAt(0)).getChildAt(0)).getChildAt(2);//获取最后一位的宽度

            //年的最大值为2100
            //月的最大值为11
            //日的最大值为28,29,30,31
            int value0 = view0.getMaxValue();//获取第一个View的最大值
            int value1 = view1.getMaxValue();//获取第二个View的最大值
            int value2 = view2.getMaxValue();//获取第三个View的最大值

            if (state == 1) {//隐藏年, 只显示月和日
                if (value0 > 252) {
                    view0.setVisibility(View.GONE);
                } else if (value1 > 252) {
                    view1.setVisibility(View.GONE);
                } else if (value2 > 252) {
                    view2.setVisibility(View.GONE);
                }
            } else if (state == 2) {//隐藏日, 只显示年和月
                if (value0 > 25 && value0 < 252) {
                    view0.setVisibility(View.GONE);
                } else if (value1 > 25 && value1 < 252) {
                    view1.setVisibility(View.GONE);
                } else if (value2 > 25 && value2 < 252) {
                    view2.setVisibility(View.GONE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示时间选择器  时分
     */
    public static void showTimerPickerDialog(Context context, boolean themeLight, String title, int hourOfDay
            , int minute, boolean is24HourView, final OnTimerPickerListener onTimerPickerListener) {
        int themeId = AlertDialog.THEME_HOLO_LIGHT;//默认白色背景
        if (!themeLight) {
            themeId = AlertDialog.THEME_HOLO_DARK;//黑色背景
        }
        showTimerPickerDialog(context, themeId, title, hourOfDay, minute, is24HourView, onTimerPickerListener);
    }
    /**
     * 显示时间选择器  时分,分钟显示有间隔
     */
    public static void showTimerPickerDialog(Context context, boolean themeLight, String title, int hourOfDay
            , int minute, boolean is24HourView, final OnTimerPickerListener onTimerPickerListener,int interval,String[] name) {
        int themeId = AlertDialog.THEME_HOLO_LIGHT;//默认白色背景
        if (!themeLight) {
            themeId = AlertDialog.THEME_HOLO_DARK;//黑色背景
        }
        showTimerPickerDialog(context, themeId, title, hourOfDay, minute, is24HourView, onTimerPickerListener, interval,name);
    }

    /**
     * 显示时间选择器, 默认白色背景
     */
    public static void showTimerPickerDialog(Context context, String title, int hourOfDay, int minute, boolean is24HourView, final OnTimerPickerListener onTimerPickerListener) {
        showTimerPickerDialog(context, AlertDialog.THEME_HOLO_LIGHT, title, hourOfDay, minute, is24HourView, onTimerPickerListener);
    }

    /**
     * 显示时间选择器
     */


    public static void showTimerPickerDialog(Context context, int themeId, String title, int hourOfDay,
                                             int minute, boolean is24HourView, final OnTimerPickerListener onTimerPickerListener) {


        //----
        TimePickerDialog dialog = new TimePickerDialog(context, themeId, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                if (onTimerPickerListener != null) {
                    onTimerPickerListener.onConfirm(hourOfDay, minute);
                }
            }
        }, hourOfDay, minute, is24HourView);

        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (onTimerPickerListener != null) {
                    onTimerPickerListener.onCancel();
                }
            }
        });

        if (!TextUtils.isEmpty(title)) {
            dialog.setTitle(title);
        }
        dialog.show();
    }


    /**
     * 时间选择器,但是分钟是间隔10分一跳动
     * @param context  上下文,
     * @param themeId  显示样式
     * @param title   表头
     * @param hourOfDay  小时
     * @param minute   分钟
     * @param is24HourView  是否24小时
     * @param onTimerPickerListener  返回
     */
    public static void showTimerPickerDialog(Context context, int themeId, String title, int hourOfDay,
                                             int minute, boolean is24HourView, final OnTimerPickerListener onTimerPickerListener,int interval, String[] name) {


        //----
        CustomTimePickerDialog dialog = new CustomTimePickerDialog(context, themeId, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                if (onTimerPickerListener != null) {
                    onTimerPickerListener.onConfirm(hourOfDay, minute);
                }
            }
        }, hourOfDay, minute, is24HourView,interval,name);

        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (onTimerPickerListener != null) {
                    onTimerPickerListener.onCancel();
                }
            }
        });

        if (!TextUtils.isEmpty(title)) {
            dialog.setTitle(title);
        }
        dialog.show();
    }


    /**
     * 日期选择器监听
     */
    public interface OnDatePickerListener {
        void onConfirm(int year, int month, int dayOfMonth);

        void onCancel();
    }

    /**
     * 时间选择器监听
     */
    public interface OnTimerPickerListener {
        void onConfirm(int hourOfDay, int minute);

        void onCancel();

    }



}

在需要的地方进行调用,这个是调整间隔10的调用

  /**
     * //开始时分选择
     * @param hour_day  小时
     * @param minute     分钟
     */
   public void setTimes( final int hour_day, final int minute){
    BasisTimesUtils.showTimerPickerDialog(activity, false, "请选择时间", hour_day, minute, true, new BasisTimesUtils.OnTimerPickerListener() {
        @Override
        public void onConfirm(int hourOfDay, int minute) {
            String months;
            String dayOfMonths;
            if (hourOfDay<10){
                months="0"+hourOfDay;
            }else {
                months=hourOfDay+"";
            }
            if (minute<10){
                dayOfMonths="0"+minute;
            } else {
                dayOfMonths=""+minute;
            }

            String times=months+":"+dayOfMonths;


            timecontrast.setTime(times);
        }
        @Override
        public void onCancel() {

        }
    },10,name);
}

年月日选择器的调用,因为返回04月这种不会带0,所以需要自己判断进行添加

  /**
     *  开始2  年月日选择1开始时间
     * @param year  年
     * @param months  月
     * @param day  日
     */
    public void showYearMonthPickerStart2(int year, final int months, final int day) {
        BasisTimesUtils.showDatePickerDialog(activity, BasisTimesUtils.THEME_HOLO_DARK,
                "请选择年月日", year, months, day, new BasisTimesUtils.OnDatePickerListener() {

                    @Override
                    public void onConfirm(int year, int month, int dayOfMonth) {
                        if (month<=months&&dayOfMonth<=day) {
                            String months;
                            String dayOfMonths;
                            if (month < 10) {
                                months = "0" + month;
                            } else {
                                months = month + "";
                            }
                            if (dayOfMonth < 10) {
                                dayOfMonths = "0" + dayOfMonth;
                            } else {
                                dayOfMonths = "" + dayOfMonth;
                            }

                            String times = year + "-" + months + "-" + dayOfMonths;


                            timecontrast.setTimeEnd(times);
                        }else {
                            ToastUtils.showShortToast(activity,"请选择有效的时间");
                        }
                    }

                    @Override
                    public void onCancel() {
//                ToastUtils.showShortToast(mView.getActivity(),"cancle");
                    }
                });

    }

获得指定日期的后一天,基本上用来带入时间段

/**
 * 获得指定日期的后一天
 * @param specifiedDay  传入时间字符串 2019-5-29
 * @return
 */
public static String getSpecifiedDayAfter(String specifiedDay){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    Date date=null;
    try {
        date = sdf.parse(specifiedDay);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    calendar.setTime(date);
    int day=calendar.get(Calendar.DATE);
    //  调整后面的+1可以切换前一天或者后一天等 此处修改为+1则是获取后一天
    calendar.set(Calendar.DATE,day+1);

    String lastDay = sdf.format(calendar.getTime());
    return lastDay;

}

调用方法只要放到任何一个点击事件里就可以,显示的是弹窗状态,可以直接复制粘贴就能使用,简单无脑。

猜你喜欢

转载自blog.csdn.net/Liu_ser/article/details/89677554