The Wayback Machine - https://web.archive.org/web/20240930205141/https://www.geeksforgeeks.org/implement-customized-timepicker-in-android-using-snaptimepicker/
Open In App

Implement customized TimePicker in Android using SnapTimePicker

Last Updated : 25 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Android TimePicker is a user interface control for selecting the time in either 24-hour format or AM/PM mode. It is used to ensure that users pick a valid time for the day in the application. The default TimePicker can be customized by using the SnapTimePicker in Android.


Some features of SnapTimePicker are:

  • Selectable time range support.
  • Text and color customization.
  • IOS Time Picker like with Material Design style.

Approach

Step 1: Add the support Library in build.gradle file and add dependency in the dependencies section. XML

implementation 'com.akexorcist:snap-time-picker:1.0.0'      

Step 2: Add the following code in string.xml file in values directory. In this file add all string used in the app. These string can be referenced from app or some other resource files(such as XML layout). string.xml

 
<resources>
    <string name="app_name">GFG | SnapTimePicker</string>
    <string name="title">Please select the time</string>
    <string name="selected_time_prefix">Your selected time is</string>

    <!-- %1$s:%2$s will add the string in HH:MM format 
    for more understanding follow the link at the end -->
    <string name="selected_time_format">%1$s:%2$s</string>

    <!-- >> means >> for more understanding follow 
    the link at the end -->
    <string name="time_prefix">>></string>

    <!-- << means << for more understanding follow 
    the link at the end -->
    <string name="time_suffix"><<</string>
</resources>       

Step 3: Add the following code in activity_main.xml file. In this file add the Buttons to select the time and the TextView to display the selected time. activity_main.xml

 
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:orientation="vertical"
        android:padding="30dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Your selected time is"
            android:textSize="16sp"/>

        <TextView
            android:id="@+id/selectedTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"/>
    </LinearLayout>

    <Button
        android:id="@+id/defaultTimePicker"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginStart="104dp"
        android:layout_marginBottom="112dp"
        android:text="Default Time Picker"
        android:textAllCaps="false"
        app:layout_constraintBottom_toTopOf="@+id/customTimePicker"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/customTimePicker"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginStart="104dp"
        android:layout_marginBottom="212dp"
        android:text="Custom Time Picker"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Step 4: Add the following code in MainActivity.kt file. In this file add onClickListener() method to the buttons so that whenever user click on them a TimePicker dialog will be created. MainActivity.kt

package com.madhav.maheshwari.snaptimepicker

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.akexorcist.snaptimepicker.SnapTimePickerDialog
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        defaultTimePicker.setOnClickListener {
            // Default TimePicker
            SnapTimePickerDialog.Builder().apply {
                setTitle(R.string.title)
                setTitleColor(android.R.color.white)
            }.build().apply {
                setListener {
                    // when the user select time onTimePicked
                    // function get invoked automatically which
                    // sets the time in textViewTime.
                        hour, minute ->
                    onTimePicked(hour, minute)
                }
            }.show(
                supportFragmentManager,
                SnapTimePickerDialog.TAG
            )
        }

        customTimePicker.setOnClickListener {
            // Custom TimePicker
            SnapTimePickerDialog.Builder().apply {
                setTitle(R.string.title)
                setPrefix(R.string.time_prefix)
                setSuffix(R.string.time_suffix)
                setThemeColor(R.color.colorAccent)
                setTitleColor(android.R.color.black)
            }.build().apply {
                setListener {
                    // when the user select time onTimePicked
                    // function get invoked automatically which
                    // sets the time in textViewTime.
                        hour, minute ->
                    onTimePicked(hour, minute)
                }
            }.show(
                supportFragmentManager,
                SnapTimePickerDialog.TAG
            )
        }

    }

    private fun onTimePicked(selectedHour: Int, selectedMinute: Int) {
        // Pads the string to the specified length
        // at the beginning with the specified
        // character or space.
        val hour = selectedHour.toString()
            .padStart(2, '0')
        val minute = selectedMinute.toString()
            .padStart(2, '0')
        selectedTime.text = String.format(
            getString(
                R.string.selected_time_format,
                hour, minute
            )
        )
    }
}

Output: Run on Emulator

    Advantages:

    • The advantages of using SnapTimePicker over simple TimePicker are:
      • SnapTimePicker can be customized according to the requirements.
      • It is very easy to use.
      • It gives IOS feel of an app.



Previous Article
Next Article

Similar Reads

TimePicker in Android
TimePicker Dialog is used in many applications where we have to book appointments based on a specific time. This widget is seen in the applications where we have to select specific time slots. In this article, we will take a look at How to use TimePicker Dialog on Android. Note: This Android article covered in both Java and Kotlin languages. Step b
4 min read
TimePicker.OnTimeChangedListener() in Android
onTimeChangedListener is a method that is called when time is edited or changed inside a TimePicker. TimePicker is an essential class provided by Android Developers. The callback interface is used to indicate the time has been adjusted. It can be helpful for providing instantaneous clock field responses. Syntax For Java: public abstract void onTime
3 min read
How to create customized Buttons in Android with different shapes and colors
A Button is a user interface that are used to perform some action when clicked or tapped. In this article, we will try to change the shape and color of Button to various designs, like: Oval Button Rectangular Button Cylindrical Button Approach: Below are the various steps to created customized Buttons: Step 1: Start a new Android Studio project Ple
4 min read
Customized Debugging in Sublime Text using C++ for Competitive Programming
Competitive Programming is a mental sport that enables us to code a given problem under provided constraints. The purpose of this article is to guide every individual on how they can debug their code efficiently during a contest.Prerequisite: Setting up Sublime Text for C++ Competitive Programming Environment Time is something that is precious and
15+ min read
TimePicker in Kotlin
Android TimePicker is a user interface control for selecting the time in either 24-hour format or AM/PM mode. It is used to ensure that users pick the valid time for the day in our application. In android, TimePicker is available in two modes first one is clock mode and another one is spinner mode. We can use TimePicker manually in XML layout or we
4 min read
Dynamic TimePicker in Kotlin
Android TimePicker is a user interface control for selecting the time in either 24-hour format or AM/PM mode. It is used to ensure that users pick a valid time for the day in our application. In android, TimePicker is available in two modes first one is clock mode and another one is spinner mode. In this article, we should create TimePicker widget
3 min read
Create a customized data structure which evaluates functions in O(1)
Create a customized data structure such that it has functions :- GetLastElement(); RemoveLastElement(); AddElement() GetMin() All the functions should be of O(1) Question Source : amazon interview questions Approach : create a custom stack of type structure with two elements, (element, min_till_now) implement the functions on this custom data type
7 min read
Implement Different Types of AlertBox using Alerter Library in Android
In this article, we are going to implement a very important feature related to the AlertBox. Usually, we create an AlertBox to show some important content. Here we are going to learn how to implement that feature in our Android App using Alert Library. A sample video is given below to get an idea about what we are going to do in this article. Note
5 min read
Implement Caching in Android Using RxJava Operators
The cache on your Android phone is a collection of little pieces of information that your apps and web browser utilize to improve efficiency. RxOperator is essentially a function that specifies the observable, as well as how and when it should emit the data stream. In RxJava, there are hundreds of operators to choose from. The majority of operators
5 min read
How to Implement Offline Caching using NetworkBoundResource in Android?
Almost, every android application that requires fetching data over a network, needs caching. First, let understand What does caching means? Most of us have used applications that require the data to be fetched from the web. Such an application with an offline-first architecture will always try to fetch the data from the local storage. On the other
11 min read
Implement IME Action Buttons in Soft Keyboard in Android using Jetpack Compose
In Android, IME (Input Method Action) Action Button is a key on the Soft Keyboard that represents different actions that can be displayed. In the below image, we have located the IME Action Buttons of two different types. In the below image, you can see the different types of actions that can be displayed in the IME Action Button on the Soft Keyboa
3 min read
Implement Markdown Text in Android using Jetpack Compose
Markdown is a third-party git library that can be used to identify particular types of regex (Regular Expressions) that specifies a search pattern in the text. For example, if you write a passage and mention a website and a telephone number in it, Markdown Text would detect these patterns and create a hyperlink around them to open them in their res
3 min read
Implement Vertical and Horizontal Draggable Modifier in Android using Jetpack Compose
In Jetpack Compose, a Draggable modifier is a modifier similar to scrollable, which is the high-level entry point to drag gestures in a single orientation and report the drag distance in pixels. Draggable modifier can be implemented on top of any element. Users can hold the element state and drag it vertically and horizontally. In this article, we
3 min read
Implement Google Admob Banner Ads in Android using Kotlin
There are several ways to earn money from mobile applications such as selling products online through applications or simply displaying ads within applications. There are so many types of ads that we can display within our application. Google provides us a service known as Google Admob with the help of which we can display ads within our applicatio
3 min read
Implement Android Pull-to-Refresh with ListVIew using Kotlin
Swipe to Refresh Layout is used in most social media applications such as Facebook or Instagram. In these applications, users can simply swipe down to refresh the posts or feeds within the applications to load the new ones. Swipe to refresh layout detects vertical swipe and displays a progress bar. After that, the listview will be updated with the
8 min read
Implement Google Admob Interstitial Ads in Android using Kotlin
There are several ways to earn money from mobile applications such as selling products online through applications or simply displaying ads within applications. There are so many types of ads that we can display within our application. Google provides us a service known as Google Admob with the help of which we can display ads within our applicatio
3 min read
Implement Universal Image Loader Library in Android using Kotlin
Universal Image Loader library is also referred to as (UIL). It is similar to Picasso and Glide which is used to load the images from the URL within our image view inside our android application. This image loading library has been created to provide a powerful, flexible, and customizable solution to load images in Android from Server. This image l
4 min read
How to Implement Press Back Again to Exit in Android using Jetpack Compose?
The back button is used in many android applications. It is generally used to navigate to the previous page or simply exit the application. Many applications nowadays ask users to press the back button twice to exit the application. In this article, we will be building a simple application in which we will implement press back again to exit the and
4 min read
Android - Implement Night Mode using Switch
Night Mode (also known as Black Mode or Dark Mode) is a screen display that uses dark background. Opposite to Light Mode which uses light background and dark text, night mode uses a dark background and light text. Dark mode reduces battery consumption, this is because the device finds it easier to run the dark background as it does not have to ligh
2 min read
How to Implement Pagination in Android RecyclerView using Volley?
Pagination is one of the most important factors which helps to reduce the loading time inside our app and increase the performance of our data which is represented in the form of Lists. In this article, we will take a look at adding pagination in our Android RecyclerView. And to get the data from API we are going to use the Volley library. What is
9 min read
How to Implement Tabs, ViewPager and Fragment in Android using Kotlin?
In some Android apps, Tabs are used, which allows developers to combine multiple tasks (operations) on a single activity. On the other hand, it provides a different look to that app. It is also possible to provide a different feel like left and right swipes by using ViewPager. And to implement this topic, a few terms are required such as ViewPager,
8 min read
Implement reverse AnimatedVectorDrawables using MorphView in Android
MorphView is a convenience library for reverse AnimatedVectorDrawables. The AnimatedVectorDrawables The class was introduced in API 21 and is used to animate Vector Drawables beautifully and easily. Following are some of the things that can perform with AnimatedVectorDrawable: Rotate, Scale, Translate VectorDrawables Animate the VectorDrawable such
5 min read
How to Implement Google Map Inside Fragment in Android?
In Android, the fragment is the part of Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. The UI flexibility on all devices improves the user experie
4 min read
How to implement View Shaker in Android
View Shaker is an animation in which, the UI of screen vibrates for a limited period of time. This can be implemented on the whole layout or some particular widget. It is a very common effect that developers use, especially to show incorrect credentials. View Shaker helps us to animate the widgets. Various effects can be added to it. Effects Attent
3 min read
How to implement Picture in Picture (PIP) in Android?
In this article, it is explained how to implement a Picture in Picture (PIP) in an Android application.We have seen in many apps such as Google Maps while using navigation that when we close the app, there is a floating screen that appears at the bottom right of the screen as shown in the image below. This screen is known as PIP(Picture in Picture)
3 min read
How to Implement RecyclerView in a Fragment in Android?
In Android, a fragment is a modular section of a user interface that can be combined with other fragments to create a flexible and responsive application. A fragment represents a behavior or a portion of the user interface in an Activity, which can be reused in different activities or layouts. It has its own lifecycle and can receive input events a
12 min read
Implement Zoom In or Zoom Out in Android
Zoom In and Zoom Out animations are used to enlarge and reduce the size of a view in Android applications respectively. These types of animations are often used by developers to provide a dynamic nature to the applications. Users also feel the changes happening in the application by watching these kinds of animations. XML Attributes of Scale Tag Th
4 min read
How to Implement Swipe Down to Refresh in Android
Certain applications show real-time data to the users, such as stock prices, availability of a product on online stores, etc. Showing real-time data requires continuous syncing of the application, and could be possible by implementing a program such as a thread. A Thread could be initiated by the application and update the real-time information imp
4 min read
How to Implement YoutubePlayerView Library in Android?
If you are looking to display YouTube videos inside your app without redirecting your user from your app to YouTube then this library is very helpful for you to use. With the help of this library, you can simply play videos from YouTube with the help of a video id inside your app itself without redirecting your user to YouTube. Now we will see the
8 min read
How to Implement TabLayout with Icon in Android?
TabLayout is used to implement horizontal tabs. TabLayout is introduced in the design support library to implement tabs. Tabs are created using the newTab() method of TabLayout class. The title and icon of Tabs are set through setText(int) and setIcon(int) methods of TabListener interface respectively. Tabs of layout are attached over TabLayout usi
4 min read