How to display Time Picker time on Android TextView

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

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 display Time Picker time in Android TextView.

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">

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Time"
        android:layout_centerInParent="true"/>

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:layout_below="@+id/txt"
        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.TextView;
import android.widget.TimePicker;


import java.util.Calendar;

public class DatePickerAndTimePickerActivity20 extends AppCompatActivity {
    private int hour, minute;
    private TextView txt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date_picker_and_time_picker20);
        txt = (TextView) findViewById(R.id.txt);
        Calendar calendar = Calendar.getInstance();
        hour = calendar.get(Calendar.HOUR_OF_DAY);
        minute = calendar.get(Calendar.MINUTE);
    }

    public void ShowTimePicker(View view){
        TimePickerDialog tpd = new TimePickerDialog(DatePickerAndTimePickerActivity20.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {
                String etime = new StringBuilder().append(String.format("%02d", hourOfDay)).append(":").append(String.format("%02d", minute)).toString();
                txt.setText(etime);

            }
        }, 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.