How to get time using Time Picker in Android

In this android programming source code example, we are going to get time using Time Picker in Android.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to get time using Time Picker in Android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ededed">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:layout_centerInParent="true"
        android:onClick="ShowTimePicker"
        android:text="ShowTimePicker"
        android:textColor="#ffffff"
        android:textSize="15sp"
        android:textStyle="bold" />

</RelativeLayout>

MainActivity.java

import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;


public class DatePickerAndTimePickerActivity13 extends AppCompatActivity {
    private int hour, minute;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date_picker_and_time_picker13);
        //setting default time
        hour = 00;
        minute = 00;
    }

    public void ShowTimePicker(View view){
        TimePickerDialog tpd = new TimePickerDialog(DatePickerAndTimePickerActivity13.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                String time = new StringBuilder().append(String.format("%02d", selectedHour)).append(":").append(String.format("%02d", selectedMinute)).toString();
                Toast.makeText(DatePickerAndTimePickerActivity13.this, time,Toast.LENGTH_LONG).show();
            }
        }, hour, minute, true);
        tpd.show();

    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment