Material Design Time Picker in Android - GeeksforGeeks

06 Jun, 2021
Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. If you like the way how the UI elements from Google Material Design Components for android which are designed by Google are pretty awesome, then here are some steps that need to be followed to get them, and one of them is Time Picker. It is not the same as that of the regular time picker in android and allows a lot of customization to improve User Experience. It gives an immense experience for the user. So in this article, it’s been discussed how to implement the Material Design Time Picker in android. Have a look at the following image on what all the perspectives the Material Design Time Picker can appear.
Step 1: Create an empty activity project
Create an empty activity android studio project. Refer to How to Create/Start a New Project in Android Studio.
Step 2: Add the required dependencies
There is a need for Material Design dependencies. To the app-level Gradle file add the following dependency.
// The version 1.3.0-alpha04 may vary
implementation ‘com.google.android.material:material:1.3.0-alpha04’
Step 3: Working with activity_main.xml file
The main layout of the application contains a button and one TextView. The Button opens the Material Design Time Picker and TextView previews the picked time.
To implement the same UI invoke the following code inside the activity_main.xml file.
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"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity"    tools:ignore="HardcodedText">      <Button        android:id="@+id/pick_time_button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="128dp"        android:text="PICK TIME"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent" />      <TextView        android:id="@+id/preview_picked_time_textView"        style="@style/TextAppearance.MaterialComponents.Headline6"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="32dp"        android:text="Preview picked time here"        app:layout_constraintEnd_toEndOf="@+id/pick_time_button"        app:layout_constraintStart_toStartOf="@+id/pick_time_button"        app:layout_constraintTop_toBottomOf="@+id/pick_time_button" />  </androidx.constraintlayout.widget.ConstraintLayout>
Output UI:
Before heading to interact with the dialog interface understanding the anatomy of dialog is important
Anatomy of the MDC Time Picker (immersive dialog).
Anatomy of the MDC Time Picker (compact).
Step 4: Working with MainActivity.kt file
In the MainActivity.kt file, handle the button click to open the Material Design Timer Picker dialog, and check for a single-digit hour and minute and update the preview text.
To implement the same invoke the following code inside the MainAactivity.kt file.
Kotlin
import android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivityimport com.google.android.material.timepicker.MaterialTimePickerimport com.google.android.material.timepicker.TimeFormat  class MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // create instance of the UI elements        val pickTimeButton: Button = findViewById(R.id.pick_time_button)        val previewPickedTimeTextView: TextView = findViewById(R.id.preview_picked_time_textView)          // handle the pick time button to open        pickTimeButton.setOnClickListener {              // instance of MDC time picker            val materialTimePicker: MaterialTimePicker = MaterialTimePicker.Builder()                // set the title for the alert dialog                .setTitleText("SELECT YOUR TIMING")                // set the default hour for the                   // dialog when the dialog opens                .setHour(12)                // set the default minute for the                  // dialog when the dialog opens                .setMinute(10)                // set the time format                   // according to the region                .setTimeFormat(TimeFormat.CLOCK_12H)                .build()              materialTimePicker.show(supportFragmentManager, "MainActivity")              // on clicking the positive button of the time picker               // dialog update the TextView accordingly            materialTimePicker.addOnPositiveButtonClickListener {                  val pickedHour: Int = materialTimePicker.hour                val pickedMinute: Int = materialTimePicker.minute                  // check for single digit hour hour and minute                  // and update TextView accordingly                val formattedTime: String = when {                    pickedHour > 12 -> {                        if (pickedMinute < 10) {                            "${materialTimePicker.hour - 12}:0${materialTimePicker.minute} pm"                        } else {                            "${materialTimePicker.hour - 12}:${materialTimePicker.minute} pm"                        }                    }                    pickedHour == 12 -> {                        if (pickedMinute < 10) {                            "${materialTimePicker.hour}:0${materialTimePicker.minute} pm"                        } else {                            "${materialTimePicker.hour}:${materialTimePicker.minute} pm"                        }                    }                    pickedHour == 0 -> {                        if (pickedMinute < 10) {                            "${materialTimePicker.hour + 12}:0${materialTimePicker.minute} am"                        } else {                            "${materialTimePicker.hour + 12}:${materialTimePicker.minute} am"                        }                    }                    else -> {                        if (pickedMinute < 10) {                            "${materialTimePicker.hour}:0${materialTimePicker.minute} am"                        } else {                            "${materialTimePicker.hour}:${materialTimePicker.minute} am"                        }                    }                }                  // then update the preview TextView                previewPickedTimeTextView.text = formattedTime            }        }    }}
Output:
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters