Time Picker Dialog - Android Studio

How to use Time Picker Dialog?

In this tutorial how to use Time Picker Dialog. We will create a button(to click to) to show Time Picker Dialog. The picked time will be displayed in a TextView.

Step 1: Create a new project OR Open your project

Step 2: Code

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context=".MainActivity" >

   <Button
       android:id="@+id/btnPickTime"
       android:text="Pick Time"
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />
   <TextView
       android:id="@+id/tvdtime"
       android:text="Picked Time will show here..."
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java
package com.blogspot.devofandroid.myapplication;

import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    Calendar mClndr;
    TimePickerDialog tpd;

    Button mBtnPickTime;
    TextView mTvTime;

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

        mTvTime = findViewById(R.id.tvdtime);
        mBtnPickTime = findViewById(R.id.btnPickTime);


        mBtnPickTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mClndr = Calendar.getInstance();
                int hour = mClndr.get(Calendar.HOUR_OF_DAY);
                int mint = mClndr.get(Calendar.MINUTE);

                tpd = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int mhour, int mMint) {
                        mTvTime.setText(mhour + ":" + mMint);
                    }
                }, hour, mint, false);
                tpd.show();
            }
        });

    }
}

Step 3: Output

 

Comments

Popular posts from this blog

Picture In Picture | Android Studio | Kotlin

Manage External Storage Permission | Android Studio | Kotlin

How to add AIDL folder | Android Studio