Android time picker library

TimePicker

Компонент TimePicker позволяет пользователю выбрать время (часы, минуты). Данный виджет используют как правило на отдельном экране. Также существует похожее по функционалу диалоговое окно TimePickerDialog.

TimePicker находился в разделе Date & Time в Android Studio 3.01. Сейчас на панели инструментов данного компонента нет, поэтому придётся добавлять вручную.

Добавим на экран текстовую метку, кнопку и компонент времени:

Пользователь может выбрать любое время на компонент, а обычный щелчок на кнопке позволит отобразить выбранное время в текстовой метке при помощи методов getHour()/getCurrentHour()) (устар. и getMinute()/getCurrentMinute() (устар.). Изменение времени можно наблюдать через слушатель OnTimeChangedListener(). Напишем пример, где программно установим время, будем отслеживать изменение времени пользователем и получать установленное время через нажатие кнопки.

Методы

Для установки и получения времени используются парные методы, которые использовались в примере:

  • setIs24HourView()
  • setCurrentHour()/getCurrentHour()
  • setCurrentMinute()/getCurrentMinute

В API 23 методы признаны устаревшими и вместо них теперь используются аналогичные методы без слова Current:

  • int getHour()
  • int getMinute()
  • void setHour(int)
  • void setMinute(int)

Новый внешний вид в Android 21 Lollipop

В Android 21 внешний вид компонента изменился.

Интересно, что ещё в августе 2013 года я написал статью на Хабре Выбираем время с помощью нового TimePickerDialog, где рассказывал о новом диалоговом окне и выражал надежду, что подобный функционал будет доступен из коробки. Мечты сбываются (с).

В 2021 году в составе библиотеки Material Design появился компонент MaterialTimePicker

Источник

Создаем красивый Date/Time/Data Picker в Android

Рано или поздно любой разработчик сталкивается с мыслью, что что-то в жизни нужно написать так, чтобы нравилось не заказчику, а самому себе. Решив, что наконец-то я созрел для написания приложения для Android, которым я сам бы пользовался с удовольствием — столкнулся с тем, что внешний вид вьюх в Android не очень-то и готов к воплощению моих красивых идей. И если обычные кнопки и TextView легко поддаются переделке, то вот с TimePicker-ом дела обстоят намного хуже. Творческая часть мозга взбунтовалась и решила, что если в приложении и будет Date/TimePicker, то такой, чтобы им было не только удобно, но и приятно пользоваться, иначе она (та самая творческая часть мозга) объявит бойкот и перестанет помогать.

Ну что же, вызов принят, напишем свой Picker с преферансом и куртизанками.


Именно такой Picker мы будем сооружать.

(Для тех кто просто хочет использовать виджет — ссылка на Git в конце статьи)

Первым делом пришлось ответить себе вопросы — а каким должен быть этот самый Picker и что он должен уметь делать?

Конечно, на вкус и цвет фломастеры разные, но если сравнить стилистику конкурирующих Picker-ов, то на мой взгляд выигрывает правый:


Time picker в Android(слева) и iOS (справа)

Пришлось отвечать для себя — а чем же привлекательнее правый Picker?

Ответ был не один:

  • Приятнее выглядит
  • Интуитивное переключение
  • Никаких лишних элементов

Но настроение хотело большего и поэтому сразу же были добавлены пункты, которые должны присутствовать в новом Picker’e.

  • Возможность легко менять размер без ущерба дизайну
  • Возможность указывать не только время но и… да вообще любую информацию
  • Все-таки должно быть более андроидным нежели яблочным

Итак, цели обозначены, приступим.

Палитра

Вообще все цвета палитры подбирались вручную перед каждым добавлением элемента. Цвета сравнивались и корректировались. В итоге получилась следующая палитра:

Названия цветов думаю сами за себя говорят, но в любом случае в коде будут пояснения, так что разобраться не составит труда.

Вставляем данный код в наш color.xml.

Создание Picker’а

Picker относится к View Элементам, значит создаем класс DataPicker:

Нам понадобятся следующие переменные:

В конструкторы возможны передачи параметров, стилей и т.д. Нам все эти излишки в рамках данной статьи не понадобятся.

Затем нам необходимо переопределить метод onSizeChanged:

Это нужно для того, чтобы при каждом изменении размера нашего холста все наши элементы прорисовывались правильно. Всегда зная размеры холста мы точно сможем заполнить все его области.

Следующим этапом необходимо определиться с возможностями нашего Picker’a. Первым делом он должен получать значения, которые необходимо отображать. Создадим для этого метод:

Для данного метода мне понадобился Handler. Дело в том, что размеры холста в момент создания равны 0 как по ширине, так и по высоте. В данном методе мы обращаемся к классу данных, в котором лежат наши значения и их параметры. Но на всякий случай проверяем, задан ли нашему холсту какой-нибудь размер. И если размер еще не определен, то просто немного отложим выполнение данной функции.

Класс со значениями и их параметрами выглядит так:

Следующая возможность, которая должна быть — это возможность изменения значения Picker’a путем скролла.

Переопределим для этого метод OnTouch:

Собственно метод выравнивания наших значений после остановки скроллинга:

Как мы видим, в прошлом методе мы использовали функцию onSelected, чтобы наш Picker сообщил о том, что пользователь выбрал какое-то значение.

Создадим для этого слушатель и определим события:

Когда все основные методы у нас определены, приступим к самому главному. Нам нужно отрисовать наш Picker на холсте. За отрисовку у нас отвечает метод onDraw:

Выглядеть это должно вот так:

С тенями уже получше:

Уже что-то интересное:

Так намного лучше:

Завершаем метод onDraw отловом ошибок и устанавливаем fps отрисовки:

Готово!

Удобство нашего Picker’a заключается в том, что мы можем их комбинировать для более удобного выбора значений.
Например, можно скомбинировать 4 компонента для выбора времени напоминания:

Дальше нашему Picker’у можно добавить обработку атрибутов, кастомные параметры, работу с адаптерами… Тут уже поле деятельности неисчерпаемо и в одной статье не разгуляться. Но если сообществу будет интересно продолжение — буду рад продолжить.

Источник

Android time picker library

Another Material Time Picker for developer who do not like default Material Time Picker that difficult to use for most users.

CustomDateTimePicker is a simple Android library for displaying a DateAndTimePicker with From and To ranges as a CustomDateTimePicker . This custom picker allow user to pick both date and time in same dialog at same time.

Читайте также:  Где находится файл permissions андроид

DateTime interval picker view for Android. All-in-one day / week / month / year picker.

Android library for horizontal single row calendar. With this library, you aren’t attached to library built-in UI. You can create really beautiful and customizable UI and use selection features without hands getting dirty with RecyclerView and SelectionTracker .

A simple vertical date picker for Android, written in Kotlin.

Scroll calendar days in a vertical column infinitely.

This awesome calendar is designed to meet more complex business requirements for Android development. And it’s easy to make a custom perfect ui. This calendar is more flexible to adapt different ui and the complicated logic.

Flutter Date Picker Library that provides a calendar as a horizontal timeline.

A helper library to make date time picker dialog easily.

A library for easy usage of TimePicker on Android API 21+

PrimeCalendar provides all java.util.Calendar functionalities for Persian and Hijri dates. PrimeCalendar can be used in every JVM-based projects such as Java/kotlin applications, Android apps, etc.

This library contains three types of calendar systems as well as their conversion to each other.

First, PrimeDatePicker is a date picker tool. It provides picking a single day in addition to a range of days. Second, it is possible to use its MonthView and CalendarView as stand alone views in your project.

A simple and customisable TimePicker created in the «old» Android API 16 style. Restyled with Material 2.0 guidelines and powered by RecyclerView .

A highly customizable calendar library for Android, powered by RecyclerView.

Date Range Picker is a Calendar Picker View to show a Customized Date Range Picker with improved UI and functionality to add subtitles to the dates.

🕋Library📗aiming to calculate 🕌prayer times 🕌 with one line code. If you implement prayer times application, there is no need to do this headache again. Islam Time prayers are every complex to calculate, cause there are many variables in calculations like:

  • latitude
  • longitude
  • timezone
  • height
  • way of calculation

An android package that provides a Horizontal Date Picker.

Источник

Android time picker library

Android SwitchDateTime Picker

SwitchDateTime Picker is a library for select a Date object in dialog with a DatePicker (Calendar) and a TimePicker (Clock) in the same UI.

You can contribute in different ways to help us on our work.

  • Add features by a pull request.
  • Help to translate into your language
  • Donate 人◕ ‿‿ ◕人Y for a better service and a quick development of your features.

Add the JitPack repository in your build.gradle at the end of repositories:

And add the dependency replacing $ with the version number in jitpack

SimpleDateFormat for Day and Month

You can specify a particular SimpleDateFormat for value of Day and Month with setSimpleDateMonthAndDayFormat(SimpleDateFormat format) Warning, the format must satisfy the regular expression : (M|w|W|D|d|F|E|u|\s)* , for example dd MMMM

By default, time is in 12 hours mode, If you want a 24-hour display, use: dateTimeFragment.set24HoursMode(true); before the «show»

Hightligh selected AM / PM

In 24 hours mode, If you want to highlight the selected AM or PM, use : dateTimeFragment.setHighlightAMPMSelection(true);

Start with a specific view

For launch Dialog with a specific view, call : dateTimeFragment.startAtTimeView(); , dateTimeFragment.startAtCalendarView(); or dateTimeFragment.startAtYearView(); before the «show»

Define minimum and maximum

For just allow selection after or/and before dates, use : dateTimeFragment.setMinimumDateTime(Date minimum); and dateTimeFragment.setMaximumDateTime(Date maximum);

Optionally define a timezone : dateTimeFragment.setTimeZone(TimeZone.getDefault());

You can customize the style to change color, bold, etc. of each element. You need to use a Theme.AppCompat theme (or descendant) with SwitchDateTime’s activity. ( compile ‘com.android.support:appcompat-v7:25.1.0’ in gradle)

In your styles.xml, you can redefine each style separately, but you must keep each item, for example : change size of «year label»

To customize the AlertDialog that is shown, use : void setAlertStyle(@StyleRes int styleId)

To use with a neutral button, initialize with another parameter and implement the OnButtonWithNeutralClickListener :

Copyright (c) 2016 JAMET Jeremy

Licensed under the Apache License, Version 2.0 (the «License»); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

About

Android library for Date and Time Picker in same dialog

Источник

Android time picker library

Material DateTime Picker — Select a time/date in style

Material DateTime Picker tries to offer you the date and time pickers as shown in the Material Design spec, with an easy themable API. The library uses the code from the Android frameworks as a base and tweaked it to be as close as possible to Material Design example.

Support for Android 4.1 and up. (Android 4.0 was supported until 3.6.4)

Feel free to fork or issue pull requests on github. Issues can be reported on the github issue tracker.

Version 2 Layout

Date Picker Time Picker

Version 1 Layout

Date Picker Time Picker

Table of Contents

The easiest way to add the Material DateTime Picker library to your project is by adding it as a dependency to your build.gradle

You may also add the library as an Android Library to your project. All the library files live in library .

The library also uses some Java 8 features, which Android Studio will need to transpile. This requires the following stanza in your app’s build.gradle . See https://developer.android.com/studio/write/java8-support.html for more information on Java 8 support in Android.

Using Material Date/Time Pickers

The library follows the same API as other pickers in the Android framework. For a basic implementation, you’ll need to

  1. Implement an OnTimeSetListener / OnDateSetListener
  2. Create a TimePickerDialog / DatePickerDialog using the supplied factory
  3. Theme the pickers

Implement an OnTimeSetListener / OnDateSetListener

In order to receive the date or time set in the picker, you will need to implement the OnTimeSetListener or OnDateSetListener interfaces. Typically this will be the Activity or Fragment that creates the Pickers. The callbacks use the same API as the standard Android pickers.

Create a TimePickerDialog / DatePickerDialog using the supplied factory

You will need to create a new instance of TimePickerDialog or DatePickerDialog using the static newInstance() method, supplying proper default values and a callback. Once the dialogs are configured, you can call show() .

Theme the pickers

The library contains 2 layout versions for each picker.

  • Version 1: this is the original layout. It is based on the layout google used in the kitkat and early material design era
  • Version 2: this layout is based on the guidelines google posted when launching android marshmallow. This is the default and still the most current design.

You can set the layout version using the factory

The pickers will be themed automatically based on the current theme where they are created, based on the current colorAccent . You can also theme the dialogs via the setAccentColor(int color) method. Alternatively, you can theme the pickers by overwriting the color resources mdtp_accent_color and mdtp_accent_color_dark in your project.

The exact order in which colors are selected is as follows:

  1. setAccentColor(int color) in java code
  2. android.R.attr.colorAccent (if android 5.0+)
  3. R.attr.colorAccent (eg. when using AppCompat)
  4. R.color.mdtp_accent_color and R.color.mdtp_accent_color_dark if none of the others are set in your project

The pickers also have a dark theme. This can be specified globablly using the mdtp_theme_dark attribute in your theme or the setThemeDark(boolean themeDark) functions. The function calls overwrite the XML setting.

[All] setThemeDark(boolean themeDark)

The dialogs have a dark theme that can be set by calling

[All] setAccentColor(String color) and setAccentColor(int color)

Set the accentColor to be used by the Dialog. The String version parses the color out using Color.parseColor() . The int version requires a ColorInt bytestring. It will explicitly set the color to fully opaque.

[All] setOkColor() and setCancelColor()

Set the text color for the OK or Cancel button. Behaves similar to setAccentColor()

[TimePickerDialog] setTitle(String title)

Shows a title at the top of the TimePickerDialog

[DatePickerDialog] setTitle(String title)

Shows a title at the top of the DatePickerDialog instead of the day of the week

[All] setOkText() and setCancelText()

Set a custom text for the dialog Ok and Cancel labels. Can take a resourceId of a String. Works in both the DatePickerDialog and TimePickerDialog

[DatePickerDialog] setMinDate(Calendar day)

Set the minimum valid date to be selected. Date values before this date will be deactivated

[DatePickerDialog] setMaxDate(Calendar day)

Set the maximum valid date to be selected. Date values after this date will be deactivated

[TimePickerDialog] setMinTime(Timepoint time)

Set the minimum valid time to be selected. Time values earlier in the day will be deactivated

[TimePickerDialog] setMaxTime(Timepoint time)

Set the maximum valid time to be selected. Time values later in the day will be deactivated

[TimePickerDialog] setSelectableTimes(Timepoint[] times)

You can pass in an array of Timepoints . These values are the only valid selections in the picker. setMinTime(Timepoint time) , setMaxTime(Timepoint time) and setDisabledTimes(Timepoint[] times) will further trim this list down. Try to specify Timepoints only up to the resolution of your picker (i.e. do not add seconds if the resolution of the picker is minutes).

[TimePickerDialog] setDisabledTimes(Timepoint[] times)

You can pass in an array of Timepoints . These values will not be available for selection. These take precedence over setSelectableTimes and setTimeInterval . Be careful when using this without selectableTimes: rounding to a valid Timepoint is a very expensive operation if a lot of consecutive Timepoints are disabled. Try to specify Timepoints only up to the resolution of your picker (i.e. do not add seconds if the resolution of the picker is minutes).

[TimePickerDialog] setTimeInterval(int hourInterval, int minuteInterval, int secondInterval)

Set the interval for selectable times in the TimePickerDialog. This is a convenience wrapper around setSelectableTimes . The interval for all three time components can be set independently. If you are not using the seconds / minutes picker, set the respective item to 60 for better performance.

[TimePickerDialog] setTimepointLimiter(TimepointLimiter limiter)

Pass in a custom implementation of TimeLimiter Disables setSelectableTimes , setDisabledTimes , setTimeInterval , setMinTime and setMaxTime

[DatePickerDialog] setSelectableDays(Calendar[] days)

You can pass a Calendar[] to the DatePickerDialog . The values in this list are the only acceptable dates for the picker. It takes precedence over setMinDate(Calendar day) and setMaxDate(Calendar day)

[DatePickerDialog] setDisabledDays(Calendar[] days)

The values in this Calendar[] are explicitly disabled (not selectable). This option can be used together with setSelectableDays(Calendar[] days) : in case there is a clash setDisabledDays(Calendar[] days) will take precedence over setSelectableDays(Calendar[] days)

[DatePickerDialog] setHighlightedDays(Calendar[] days)

You can pass a Calendar[] of days to highlight. They will be rendered in bold. You can tweak the color of the highlighted days by overwriting mdtp_date_picker_text_highlighted

[DatePickerDialog] showYearPickerFirst(boolean yearPicker)

Show the year picker first, rather than the month and day picker.

[All] OnDismissListener and OnCancelListener

Both pickers can be passed a DialogInterface.OnDismissLisener or DialogInterface.OnCancelListener which allows you to run code when either of these events occur.

[All] vibrate(boolean vibrate)

Set whether the dialogs should vibrate the device when a selection is made. This defaults to true .

[All] dismissOnPause(boolean dismissOnPause)

Set whether the picker dismisses itself when the parent Activity is paused or whether it recreates itself when the Activity is resumed.

[All] setLocale(Locale locale)

Allows the client to set a custom locale that will be used when generating various strings in the pickers. By default the current locale of the device will be used. Because the pickers will adapt to the Locale of the device by default you should only have to use this in very rare circumstances.

[DatePickerDialog] autoDismiss(boolean autoDismiss)

If set to true will dismiss the picker when the user selects a date. This defaults to false .

[TimepickerDialog] enableSeconds(boolean enableSconds) and enableMinutes(boolean enableMinutes)

Allows you to enable or disable a seconds and minutes picker on the TimepickerDialog . Enabling the seconds picker, implies enabling the minutes picker. Disabling the minute picker will disable the seconds picker. The last applied setting will be used. By default enableSeconds = false and enableMinutes = true .

[DatePickerDialog] setTimeZone(Timezone timezone) deprecated

Sets the Timezone used to represent time internally in the picker. Defaults to the current default Timezone of the device. This method has been deprecated: you should use the newInstance() method which takes a Calendar set to the appropriate TimeZone.

[DatePickerDialog] setDateRangeLimiter(DateRangeLimiter limiter)

Provide a custom implementation of DateRangeLimiter, giving you full control over which days are available for selection. This disables all of the other options that limit date selection.

getOnTimeSetListener() and getOnDateSetListener()

Getters that allow the retrieval of a reference to the callbacks currently associated with the pickers

[DatePickerDialog] setScrollOrientation(ScrollOrientation scrollOrientation) and getScrollOrientationi()

Determines whether months scroll Horizontal or Vertical . Defaults to Horizontal for the v2 layout and Vertical for the v1 layout

Why does the DatePickerDialog return the selected month -1?

In the java Calendar class months use 0 based indexing: January is month 0, December is month 11. This convention is widely used in the java world, for example the native Android DatePicker.

How do I use a different version of a support library in my app?

This library depends on some androidx support libraries. Because the jvm allows only one version of a fully namespaced class to be loaded, you will run into issues if your app depends on a different version of a library than the one used in this app. Gradle is generally quite good at resolving version conflicts (by default it will retain the latest version of a library), but should you run into problems (eg because you disabled conflict resolution), you can disable loading a specific library for MaterialDateTimePicker.

Using the following snippet in your apps build.gradle file you can exclude this library’s transitive appcompat library dependency from being installed.

MaterialDateTimepicker uses the following androidx libraries:

Excluding a dependency will work fine as long as the version your app depends on is recent enough and google doesn’t release a version in the future that contains breaking changes. (If/When this happens I will try hard to document this). See issue #338 for more information.

How do I turn this into a year and month picker?

This DatePickerDialog focuses on selecting dates, which means that it’s central design element is the day picker. As this calendar like view is the center of the design it makes no sense to try and disable it. As such selecting just years and months, without a day, is not in scope for this library and will not be added.

How do I select multiple days?

The goal of this library is to implement the Material Design Date picker. This design is focused on picking exactly 1 date (with a large textual representation at the top). It would require quite a bit of redesigning to make it useful to select multiple days. As such this feature is currently out of scope for this library and will not be added. If you happen to make a library that implements this, based on this code or not, drop me a line and I’ll happily link to it.

How do I use my custom logic to enable/disable dates?

DatePickerDialog exposes some utility methods to enable / disable dates for common scenario’s. If your needs are not covered by these, you can supply a custom implementation of the DateRangeLimiter interface. Because the DateRangeLimiter is preserved when the Dialog pauzes, your implementation must also implement Parcelable .

When you provide a custom DateRangeLimiter the built-in methods for setting the enabled / disabled dates will no longer work. It will need to be completely handled by your implementation.

Why do the OK and Cancel buttons have the accent color as a background when combined with the Material Components library

Material Components replaces all instances of Button with an instance of MaterialButton when using one of its regular themes: https://github.com/material-components/material-components-android/blob/master/docs/getting-started.md#material-components-themes
The default version of MaterialButton uses colorPrimary as the background color. Because Material Components replaces the View replacer with their own implementation there is not much I can do to fix this from this library.

There are a few workarounds:

  • Use one of the bridge themes, which do not replace the View Inflater
  • Overwrite the style of the mdtp buttons with one that inherits from Material Components text buttons, as described here:

Why are my callbacks lost when the device changes orientation?

The simple solution is to dismiss the pickers when your activity is paused.

If you do wish to retain the pickers when an orientation change occurs, things become a bit more tricky.

By default, when an orientation changes occurs android will destroy and recreate your entire Activity . Wherever possible this library will retain its state on an orientation change. The only notable exceptions are the different callbacks and listeners. These interfaces are often implemented on Activities or Fragments . Naively trying to retain them would cause memory leaks. Apart from explicitly requiring that the callback interfaces are implemented on an Activity , there is no safe way to properly retain the callbacks, that I’m aware off.

This means that it is your responsibility to set the listeners in your Activity ‘s onResume() callback.

Источник

Оцените статью