DatePicker:日期滚动选择

效果图为:
DatePicker:日期滚动选择_第1张图片

1.dialog_date.xml:




    

        

        

        

    

    


DatePicker:日期滚动选择_第2张图片
布局里看起来还不是滚动式的,但所有工作弄完后,就是滚动啦

2.对应的MyDatePicker类:

public class MyDatePicker implements DatePicker.OnDateChangedListener,
        TimePicker.OnTimeChangedListener {

    /**
     * 定义结果回调接口
     */
    public interface ResultHandler {
        void handle(String time);
    }

    private DatePicker datePicker;
    private TextView tv_ok;
    private TextView tv_cancle;

    private ResultHandler handler;
    private String dateTime;
    private Context context;
    private String initDateTime;

    private Dialog datePickerDialog;

    public MyDatePicker(Context context, ResultHandler resultHandler, String initDateTime) {
        this.context = context;
        this.handler = resultHandler;
        this.initDateTime = initDateTime;
        initDialog();
    }

    private void initDialog() {
        if (datePickerDialog == null) {
            datePickerDialog = new Dialog(context, R.style.mytime_dialog);
//            datePickerDialog = new Dialog(context);
            datePickerDialog.setCancelable(false);
            datePickerDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            datePickerDialog.setContentView(R.layout.dialog_date);
            Window window = datePickerDialog.getWindow();
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.dialogWindowAnim); //设置窗口弹出动画
            WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics dm = new DisplayMetrics();
            manager.getDefaultDisplay().getMetrics(dm);
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = dm.widthPixels;
            window.setAttributes(lp);
        }
        initView();
    }

    private void initView() {
        datePicker = (DatePicker) datePickerDialog.findViewById(R.id.datepicker);
        tv_ok = (TextView) datePickerDialog.findViewById(R.id.tv_ok);
        tv_cancle = (TextView) datePickerDialog.findViewById(R.id.tv_cancle);

        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                datePickerDialog.dismiss();
            }
        });

        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handler.handle( dateTime );
                datePickerDialog.dismiss();
            }
        });

        datePickerDialog.show();
        initDate(datePicker);
    }

    public void initDate(DatePicker datePicker) {
        Calendar calendar = Calendar.getInstance();
        if (!(null == initDateTime || "".equals(initDateTime))) {
            calendar = this.getCalendarByInintData(initDateTime);
        } else {
            initDateTime = calendar.get(Calendar.YEAR) + "年"
                    + calendar.get(Calendar.MONTH) + "月"
                    + calendar.get(Calendar.DAY_OF_MONTH) + "日 "
                    + calendar.get(Calendar.HOUR_OF_DAY) + ":"
                    + calendar.get(Calendar.MINUTE);
        }

        datePicker.init(calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), this);
    }

    /**
     * 实现将初始日期时间2012年07月02日 16:45 拆分成年 月 日 时 分 秒,并赋值给calendar
     *
     * @param initDateTime
     *            初始日期时间值 字符串型
     * @return Calendar
     */
    private Calendar getCalendarByInintData(String initDateTime) {
        Calendar calendar = Calendar.getInstance();

        // 将初始日期时间2012年07月02日 16:45 拆分成年 月 日 时 分 秒
        String date = spliteString(initDateTime, "日", "index", "front"); // 日期
        String time = spliteString(initDateTime, "日", "index", "back"); // 时间

        String yearStr = spliteString(date, "年", "index", "front"); // 年份
        String monthAndDay = spliteString(date, "年", "index", "back"); // 月日

        String monthStr = spliteString(monthAndDay, "月", "index", "front"); // 月
        String dayStr = spliteString(monthAndDay, "月", "index", "back"); // 日

        String hourStr = spliteString(time, ":", "index", "front"); // 时
        String minuteStr = spliteString(time, ":", "index", "back"); // 分

        int currentYear = Integer.valueOf(yearStr.trim()).intValue();
        int currentMonth = Integer.valueOf(monthStr.trim()).intValue() - 1;
        int currentDay = Integer.valueOf(dayStr.trim()).intValue();
        int currentHour = Integer.valueOf(hourStr.trim()).intValue();
        int currentMinute = Integer.valueOf(minuteStr.trim()).intValue();

        calendar.set(currentYear, currentMonth, currentDay, currentHour,
                currentMinute);
        return calendar;
    }

    /**
     * 截取子串
     *
     * @param srcStr
     *            源串
     * @param pattern
     *            匹配模式
     * @param indexOrLast
     * @param frontOrBack
     * @return
     */
    public static String spliteString(String srcStr, String pattern,
                                      String indexOrLast, String frontOrBack) {
        String result = "";
        int loc = -1;
        if (indexOrLast.equalsIgnoreCase("index")) {
            loc = srcStr.indexOf(pattern); // 取得字符串第一次出现的位置
        } else {
            loc = srcStr.lastIndexOf(pattern); // 最后一个匹配串的位置
        }
        if (frontOrBack.equalsIgnoreCase("front")) {
            if (loc != -1)
                result = srcStr.substring(0, loc); // 截取子串
        } else {
            if (loc != -1)
                result = srcStr.substring(loc + 1, srcStr.length()); // 截取子串
        }
        return result;
    }

    @Override
    public void onDateChanged(DatePicker datePicker, int i, int i1, int i2) {
        // 获得日历实例
        Calendar calendar = Calendar.getInstance();

        calendar.set(datePicker.getYear(), datePicker.getMonth(),
                datePicker.getDayOfMonth());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");

        dateTime = sdf.format(calendar.getTime());

    }

    @Override
    public void onTimeChanged(TimePicker timePicker, int i, int i1) {
        onDateChanged(null, 0, 0, 0);
    }

}

设置对话框样式,核心代码:

private void initDialog() {
        if (datePickerDialog == null) {
            datePickerDialog = new Dialog(context, R.style.mytime_dialog);
//            datePickerDialog = new Dialog(context);
            datePickerDialog.setCancelable(false);
            datePickerDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            datePickerDialog.setContentView(R.layout.dialog_date);
            Window window = datePickerDialog.getWindow();
            window.setGravity(Gravity.BOTTOM);//使对话框出现在底部
            window.setWindowAnimations(R.style.dialogWindowAnim); //设置窗口弹出动画
            WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics dm = new DisplayMetrics();
            manager.getDefaultDisplay().getMetrics(dm);
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = dm.widthPixels;
            window.setAttributes(lp);
        }
        initView();
    }

定义对话框style风格和添加动画:



    

dialog_enter_anim.xml的代码:




    

dialog_exit_anim.xml的代码:




    

3.在主界面activity中需要使用日期对话框的地方,调用函数initMyDatePicker()即可:

private void initMyDatePicker() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日    HH:mm");//格式为 2013年9月3日 14:44
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String currentDate = formatter.format(curDate);

        myDatePicker = new MyDatePicker(this, new MyDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                tv_showCurrentDate1.setText(time );
            }
        },currentDate);
    }

注:DatePicker的样式会受主题的样式影响,写的时候弄了好久,一定要注意才行


你可能感兴趣的:(Android之路)