【安卓开发】Android中日期选择器DatePicker和TimePicker的使用

D a t e P i c k e r DatePicker DatePicker T i m e P i c k e r TimePicker TimePicker是安卓自带的日期选择器,可以变换多种样式,下面是他们的简单使用。

显示年月日和具体时间

s p i n n e r s S h o w n spinnersShown spinnersShown设置是否显示Spinner日期选择组件
dialog_time.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <DatePicker
        android:id="@+id/date_picker"
        android:layout_width="wrap_content"
        android:layout_height="320dp"
        android:layout_marginTop="5dip"
        android:spinnersShown="false" />

    <TimePicker
        android:id="@+id/time_picker"
        android:layout_width="wrap_content"
        android:layout_height="400dp"
        android:layout_marginTop="5dip" />
</LinearLayout>

JAVA中创建 d i a l o g dialog dialog选择日期

private void showTime() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = View.inflate(getContext(), R.layout.dialog_time, null);
        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        final TimePicker timePicker = (android.widget.TimePicker) view.findViewById(R.id.time_picker);
        builder.setView(view);

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);

        timePicker.setIs24HourView(true);
        timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
        timePicker.setCurrentMinute(Calendar.MINUTE);
            builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String CurrentHour=timePicker.getCurrentHour().toString();
                    String CurrentMinute=timePicker.getCurrentMinute().toString();

                    if (timePicker.getCurrentHour() >= 0 && timePicker.getCurrentHour() <= 9) {
                        CurrentHour = "0" + timePicker.getCurrentHour() ;
                    }
                    if (timePicker.getCurrentMinute() >= 0 && timePicker.getCurrentMinute() <= 9) {
                        CurrentMinute = "0" + timePicker.getCurrentMinute();
                    }
                    StringBuffer sb = new StringBuffer();
                    sb.append(String.format("%d年%02d月%02d日",
                            datePicker.getYear(),
                            datePicker.getMonth() + 1,
                            datePicker.getDayOfMonth()));
                    sb.append("  ");
                    sb.append(CurrentHour)
                            .append(":").append(CurrentMinute)
                            .append(":00");

                    ttime=sb.toString();
                    System.out.println(ttime);
                    dialog.cancel();//取消dialog
                }
            });
        Dialog dialog = builder.create();
        dialog.show();
    }

在这里插入图片描述

只显示年月

dialog_his.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <DatePicker
        android:id="@+id/date_picker_his"
        android:layout_width="wrap_content"
        android:layout_height="320dp"
        android:layout_marginTop="5dip"
        android:calendarViewShown="false"
        android:datePickerMode="spinner" />
</LinearLayout>

JAVA

private void show() {
        System.out.println("点击了日历");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = View.inflate(this, R.layout.dialog_his, null);
        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker_his);
        builder.setView(view);

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);
        hideDay(datePicker);
        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                year=datePicker.getYear();
                month=datePicker.getMonth()+1;
                ShowData();
                System.out.println(year+"年"+month+"月");
                dialog.cancel();//取消dialog
            }
        });
        Dialog dialog = builder.create();
        dialog.show();
    }
    private void hideDay(DatePicker mDatePicker) {
        try {
            /* 处理android5.0以上的特殊情况 */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                int daySpinnerId = Resources.getSystem().getIdentifier("day", "id", "android");
                if (daySpinnerId != 0) {
                    View daySpinner = mDatePicker.findViewById(daySpinnerId);
                    if (daySpinner != null) {
                        daySpinner.setVisibility(View.GONE);
                    }
                }
            } else {
                Field[] datePickerfFields = mDatePicker.getClass().getDeclaredFields();
                for (Field datePickerField : datePickerfFields) {
                    if ("mDaySpinner".equals(datePickerField.getName()) || ("mDayPicker").equals(datePickerField.getName())) {
                        datePickerField.setAccessible(true);
                        Object dayPicker = new Object();
                        try {
                            dayPicker = datePickerField.get(mDatePicker);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        }
                        ((View) dayPicker).setVisibility(View.GONE);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

在这里插入图片描述

参考博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豆沙睡不醒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值