ZOFTINO.COM android and web dev tutorials

Android TimePicker Example

Android TimePicker UI control can be used to let users pick time in android applications. Using TimePicker, applications can get valid and well formatted time. TimePicker control can be provided by using TimePickerDialog or TimePicker widget.

In this post, you can learn using TimePicker, TimePickerDialog, TimePicker widget, TimePicker material styles, TimePicker custom styles, TimePicker event handling, TimePicker clock mode, and TimePicker spinner mode.

Android TimePickerDialog Example

To show TimePicker using TimePickerDialog, you need to create a fragment by extending DialogFragment class and implementing onCreateDialog method. In onCreateDialog method, you need to instantiate TimePickerDialog setting current time and return it.

In the activity where you need to show TimePicker, you need to instantiated the Fragment and show it in response to user event such as button click.

TimePicker dialog fragment

 package dialog.zoftino.com.dialog;


import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.Calendar;

public class MyTimePickerFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        return new TimePickerDialog(getActivity(), timeSetListener, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    private TimePickerDialog.OnTimeSetListener timeSetListener =
            new TimePickerDialog.OnTimeSetListener() {
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    Toast.makeText(getActivity(), "selected time is "
                            + view.getHour() +
                            " / " + view.getMinute()
                            , Toast.LENGTH_SHORT).show();
                }
            };
}
 

Activity

 public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void showTimePickerDialog(View v) {
        DialogFragment newFragment = new MyTimePickerFragment();
        newFragment.show(getSupportFragmentManager(), "time picker");
    }
} 

TimePickerDialog example output

android timepicker dialog

Android TimePickerDialog event handling

To handle TimePickerDialog events, you need to implement TimePickerDialog.OnTimeSetListener interface which has onTimeSet callback that gets called every time user picks time using TimePicker. You can add timeSetListener to TimePickerDialog by passing it to constructor as shown in the above dialog fragment code.

TimePicker Widget Example

Instead of TimePickerDialog, you can use TimePicker widget to provide TimePicker control in your application. You can define TimePicker in layout xml using TimePicker element as shown below.

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:text="Time Picker Widget"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"  />
</android.support.constraint.ConstraintLayout>
 

In the activity, you can get the TimePicker object and set time change listener by calling setOnTimeChangedListener method and passing TimePicker.OnTimeChangedListener instance to it. TimePicker.OnTimeChangedListener interface has one callback method onTimeChanged, in this method you can get user picked time.

 public class TimePickerWidgetActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.timepicker);

        TimePicker tp = findViewById(R.id.timePicker);
        tp.setOnTimeChangedListener(timeChangedListener);
    }
    private TimePicker.OnTimeChangedListener timeChangedListener =
            new TimePicker.OnTimeChangedListener(){
                @Override
                public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                    Toast.makeText(TimePickerWidgetActivity.this,
                            "picked time is " + view.getHour() +
                            " / " + view.getMinute()
                            , Toast.LENGTH_SHORT).show();
                }
            };

}
 

TimePicker widget example output

android timepicker widget

Android TimePicker Modes

TimePicker can be used in two modes: clock and spinner mode. If you use material themes, the default TimePicker mode is clock. Above pictures show TimePicker in clock mode. You can change default setting using android:timePickerMode attribute. It takes clock or spinner as values. Below picture shows TimePicker in spinner mode.

android timepicker spinner

Android TimePicker Custom Material Style

TimePicker material style application level

You can change time picker color by defining custom colors in your custom application theme as shown below and setting it as application theme. This color change impacts not only TimePicker but also other controls throughout the application.

 <style name="MyAppThemeThree" parent="Theme.AppCompat.Light">
    <item name="colorAccent">#b71c1c</item>
    <item name="colorControlActivated">#558b2f</item>
    <item name="android:selectableItemBackgroundBorderless">@color/colorPrimaryDark</item>
</style> 

To change colors of only TimePicker control throughout the application, you need to first define custom TimePicker style and set it as theme for time picker in your application theme as shown below.

<style name="MyAppThemeFour" parent="Theme.AppCompat.Light">
    <item name="android:timePickerDialogTheme">@style/MyTimePickerDialogStyle</item>
</style>
<style name="MyTimePickerDialogStyle" parent="@style/ThemeOverlay.AppCompat.Dialog.Alert">
<item name="showTitle">false</item>
<item name="colorControlActivated">#ffd600</item>
<item name="colorAccent">#b71c1c</item>
<item name="android:textColorPrimary">#43a047</item>
<item name="android:textColorSecondary">#f44336</item>
</style> 
android timepicker custom color

Android TimePicker widget custom style

Android provides Widget.Material.TimePicker and Widget.Material.Light.TimePicker material styles for TimePicker widget. You can customize and apply these styles to TimePicker as shown below.

<style name="MyTimePickerWidgetStyle" parent="@android:style/Widget.Material.TimePicker">
    <item name="android:headerBackground">#ffe082</item>
    <item name="android:numbersTextColor">#b71c1c</item>
    <item name="android:numbersInnerTextColor">#f44336</item>
    <item name="android:numbersSelectorColor">#33691e</item>
    <item name="android:numbersBackgroundColor">#ef9a9a</item>
    <item name="android:amPmTextColor">#9c27b0</item>
</style>

Applying custom material to TimePicker.

<TimePicker
    android:id="@+id/timePicker"
    android:theme="@style/MyTimePickerWidgetStyle"
    style="@style/MyTimePickerWidgetStyle"
    . . . />

Output of TimePicker custom material style.

android timepicker widget custom color

Android TimePicker Spinner Custom Color

To change TimePicker spinner’s selection divider color, define colorControlNormal property in your custom style and apply it to TimePicker.

android timepicker spinner custom color