Android TimePicker的简单实用

3,799 阅读2分钟

这是我参与 8 月更文挑战的第 4 天,活动详情查看: 8月更文挑战

背景

上篇文章提到了项目需求要做一个年月日的选择框,由于三方库PickerView不满足需求开启了googleDatePicker之旅,这篇文章要介绍的是google的另外一个控件TimePicker

效果

Kapture 2021-08-04 at 14.56.35.gif

集成

1.在xml中插入TimePicker

<TimePicker
    android:layout_marginTop="20dp"
    android:id="@+id/time_picker"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFFFF"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@id/tv_date"/>

2.在代码中初始化并调用

//是否显示24小时视图
timePicker.setIs24HourView(false);
//设置选中的时
timePicker.setCurrentHour(2);
//设置选中的分
timePicker.setCurrentMinute(59);
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
        Log.e("onTimeChanged",hourOfDay+" "+minute);
        Calendar timeCalendar = Calendar.getInstance();
        timeCalendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
        timeCalendar.set(Calendar.MINUTE,minute);
        time.setText(android.text.format.DateFormat.getTimeFormat(getBaseContext()).format(new Date(timeCalendar.getTimeInMillis())));
    }
});

效果如下,并不能满足需求

image.png

样式调整

有了之前的经验,直接去翻文档 发现有类似的属性android:timePickerMode

Defines the look of the widget. Prior to the L release, the only choice was spinner. As of L, with the Material theme selected, the default layout is clock, but this attribute can be used to force spinner to be used instead.
Must be one of the following constant values.

大概意思就是说从Android L开始TimePicker默认样式为时钟样式,如果想调整样式android:timePickerMode就必须设置为以下两个值的其中之一

字段简介
clock2Time picker with clock face to select the time.
spinner1Time picker with spinner controls to select the time.

设置完效果如下

image.png 至此Ui基本完成

根据不同地区格式化对应的时间格式

目前我在项目中用到的方法是android.text.format.包下的DateFormat类中的方法

android.text.format.DateFormat.getTimeFormat(getBaseContext()).format(new Date(timeCalendar.getTimeInMillis()))

TimePicker常用属性

android:datePickerMode:控件显示方式 clockspinner.
getCurrentHour():获取当前选择的时间,如果minSdkVersion >=23推荐使用getHour()
getCurrentMinute():获取当前选择的分钟,如果minSdkVersion >=23推荐使用getMinute()
setCurrentHour():获取当前选择的时间,如果minSdkVersion >=23推荐使用setHour()
setCurrentMinute():获取当前选择的分钟,如果minSdkVersion >=23推荐使用setMinute()
is24HourView():获取当前组件是否为24小时模式
setIs24HourView():设置当前组件是否为24小时模式

项目地址

项目地址