Mon. Nov 25th, 2024

Android Date Time picker are used a lot in android apps. In this tutorial we’ll demonstrate the use of a Date Picker and Timer Picker Dialog in our android application. These components are used to select date and time in a customised user interface. We will use DatePickerDialog and TimePickerDialog classes with Calendar class in our android application code to achieve this.

Android DatePickerDialog and TimePickerDialog

Though a Date Picker and Time Picker can be used as independent widgets but they occupy more space on the screen. Hence using them inside a Dialog is a better choice. Fortunately android provides use with its own DatePickerDialog and TimePickerDialog classes. DatePickerDialog and TimePickerDialog classes have onDateSetListener() and onTimeSetListener() callback methods respectively. These callback methods are invoked when the user is done with filling the date and time respectively. The DatePickerDialog class consists of a 5 argument constructor with the parameters listed below.

  1. Context: It requires the application context
  2. CallBack FunctiononDateSet() is invoked when the user sets the date with the following parameters:
  • int year : It will be store the current selected year from the dialog
  • int monthOfYear : It will be store the current selected month from the dialog
  • int dayOfMonth : It will be store the current selected day from the dialog
  1. int mYear : It shows the the current year that’s visible when the dialog pops up
  2. int mMonth : It shows the the current month that’s visible when the dialog pops up
  3. int mDay : It shows the the current day that’s visible when the dialog pops up

The TimePickerDialog class consists of a 5 argument constructor with the parameters listed below.

  1. Context: It requires the application context
  2. CallBack FunctiononTimeSet() is invoked when the user sets the time with the following parameters:
  • int hourOfDay : It will be store the current selected hour of the day from the dialog
  • int minute : It will be store the current selected minute from the dialog
  1. int mHours : It shows the the current Hour that’s visible when the dialog pops up
  2. int mMinute : It shows the the current minute that’s visible when the dialog pops up
  3. boolean false : If its set to false it will show the time in 24 hour format else not

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Dialogs Example"
        />

   

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="DatePicker" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TimePicker" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>
</layout>

MainActivity.java

package com.androindian.dialog;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

import com.androindian.dialog.databinding.ActivityMainBinding;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding= DataBindingUtil.setContentView(MainActivity.this,R.layout.activity_main);


        Calendar calendar=Calendar.getInstance();
        // date
        int myear=calendar.get(Calendar.YEAR);
        int mmonth=calendar.get(Calendar.MONTH);
        int mday=calendar.get(Calendar.DAY_OF_MONTH);
//time
        int mhour=calendar.get(Calendar.HOUR_OF_DAY);
        int mmin=calendar.get(Calendar.MINUTE);
        int msec=calendar.get(Calendar.SECOND);


        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog dialog=new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

                        binding.textView.setText(dayOfMonth+"-"+month+"-"+year);

                    }
                },myear,mmonth,mday);
                dialog.getDatePicker().setMaxDate(new Date().getTime());
                dialog.show();
            }
        });

        binding.button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerDialog timePickerDialog=new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        binding.textView1.setText(hourOfDay+":"+minute);

                    }
                },mhour,mmin,false);
                timePickerDialog.show();
            }
        });
    }
}

gradle

package com.androindian.dialog;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

import com.androindian.dialog.databinding.ActivityMainBinding;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding= DataBindingUtil.setContentView(MainActivity.this,R.layout.activity_main);


        Calendar calendar=Calendar.getInstance();
        // date
        int myear=calendar.get(Calendar.YEAR);
        int mmonth=calendar.get(Calendar.MONTH);
        int mday=calendar.get(Calendar.DAY_OF_MONTH);
//time
        int mhour=calendar.get(Calendar.HOUR_OF_DAY);
        int mmin=calendar.get(Calendar.MINUTE);
        int msec=calendar.get(Calendar.SECOND);


        binding.bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Hello Good Morning");
                builder.setMessage("Are you want close");
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "Yes", Toast.LENGTH_SHORT).show();
                    }
                });
                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "No", Toast.LENGTH_SHORT).show();
                    }
                });
                builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "Cancel", Toast.LENGTH_SHORT).show();
                    }
                });

                builder.show();
            }
        });

        //custom
        binding.custom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Dialog dialog=new Dialog(MainActivity.this);
                dialog.setContentView(R.layout.custom);
                dialog.setCancelable(false);

                Button button=dialog.findViewById(R.id.btdialog);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this, "Custom dialog", Toast.LENGTH_SHORT).show();
                        dialog.cancel();
                    }
                });

                dialog.show();
            }
        });

        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog dialog=new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

                        binding.textView.setText(dayOfMonth+"-"+month+"-"+year);

                    }
                },myear,mmonth,mday);
                dialog.getDatePicker().setMaxDate(new Date().getTime());
                dialog.show();
            }
        });

        binding.button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerDialog timePickerDialog=new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        binding.textView1.setText(hourOfDay+":"+minute);

                    }
                },mhour,mmin,false);
                timePickerDialog.show();
            }
        });
    }
}

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *