DatePickerDialog in Android

Android DatePicker is a user interface control that is used to select the date by a day, month, and year in the android application. DatePicker is used to ensure that the users will select a valid date. In android DatePicker having two modes, the first one shows the complete calendar and the second one shows the dates in the spinner view. One can create a DatePicker control in two ways either manually in the XML file or create it in the Activity file programmatically. We are going to do it programmatically by using Java.

Note: To implement DatePicker using Kotlin please refer to this.

calendar mode

Approach

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.



Step 2: Working with activity_main.xml file

In the activity_main.xml file add only a TextView to display the selected date and a Button to select the date from the DatePickerDialog. Below is the complete code for the activity_main.xml file.

activity_main.xml

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <TextView
        android:id="@+id/tvDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Date" />
  
    <Button
        android:id="@+id/btPickDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvDate"
        android:layout_centerInParent="true"
        android:text="Pick Date" />
  
</RelativeLayout>

chevron_right


Step 3: Create a new class and names as DatePicker

Now create a new class by going to the package and right-click on it and select new and then Java Class. Name the class as DatePicker and its superclass as DialogFragment (androidx.fragment.app.DialogFragment) and click OK.
 

Now override a method onCreateDialog and instead of returning super.onCreateDialog return an instance of DatePickerDialog

@NonNull



   @Override

   public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

       return new DatePickerDialog();

   }

Now pass parameters to the constructor of DatePickerDialog which requires context, OnDateSetListener, year, month, dayOfMonth.

  • Pass the getActivity method for the context.
  • For OnDateSetListener typecast the getActivity method to OnDateSetListener.
  • For the year, month, and dayOfMonth create an instance of calendar class and assign the year, month, and dayOfMonth to variables of type int.
  • Pass year and month and dayOfMonth so that when the DatePickerDialog opens it has the current date.

@NonNull

@Override

public Dialog

onCreateDialog(@Nullable Bundle savedInstanceState)

{



   Calendar mCalender = Calendar.getInstance();

   int year = mCalender.get(Calendar.YEAR);

   int month = mCalender.get(Calendar.MONTH);

   int dayOfMonth = mCalender.get(Calendar.DAY_OF_MONTH);

   return new DatePickerDialog(

       getActivity(),

       (DatePickerDialog.OnDateSetListener)getActivity(),

       year, month, dayOfMonth);

}

The complete code for the DatePicker.java class is given below. 



DatePicker.java

filter_none

edit
close

play_arrow

link
brightness_4
code

package tutorials.droid.datepicker;
  
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import java.util.Calendar;
  
public class DatePicker extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Calendar mCalender = Calendar.getInstance();
        int year = mCalender.get(Calendar.YEAR);
        int month = mCalender.get(Calendar.MONTH);
        int dayOfMonth = mCalender.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener)
                getActivity(), year, month, dayOfMonth);
    }
}

chevron_right


Step 4: Working with MainActivity.java file

Now In the MainActivity.java file, create an object of both TextView and Button and map the components(TextView and Button) with their ids. 

TextView tvDate;

Button btPickDate;

tvDate = findViewById(R.id.tvDate);

btPickDate = findViewById(R.id.btPickDate);

Implement OnDateSetListener of DatePickerDialog class and override onDateSet() method.  The  onDateSet() method will set the date after selection in the tvDate TextView. 

 @Override

   public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)



 {

       // Create a Calender instance

       Calendar mCalender = Calendar.getInstance();

       // Set static variables of Calender instance

       mCalender.set(Calendar.YEAR,year);

       mCalender.set(Calendar.MONTH,month);

       mCalender.set(Calendar.DAY_OF_MONTH,dayOfMonth);

       // Get the date in form of string

       String selectedDate = DateFormat.getDateInstance(DateFormat.FULL).format(mCalender.getTime());

       // Set the textview to the selectedDate String

       tvDate.setText(selectedDate);

}

In the onClick() method implement setOnClickListener of btPickDate. Create an instance of DatePicker(our class). Use the show method of the instance and pass getSupportFragmentManager() and a Tag. The complete code for the MainActivity.java file is given below.

MainActivity.java

filter_none

edit
close

play_arrow

link
brightness_4
code

package tutorials.droid.datepicker;
  
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.text.DateFormat;
import java.util.Calendar;
  
public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
    TextView tvDate;
    Button btPickDate;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvDate = findViewById(R.id.tvDate);
        btPickDate = findViewById(R.id.btPickDate);
        btPickDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Please note that use your package name here
                tutorials.droid.datepicker.DatePicker mDatePickerDialogFragment;
                mDatePickerDialogFragment = new tutorials.droid.datepicker.DatePicker();
                mDatePickerDialogFragment.show(getSupportFragmentManager(), "DATE PICK");
            }
        });
    }
  
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        Calendar mCalender = Calendar.getInstance();
        mCalender.set(Calendar.YEAR, year);
        mCalender.set(Calendar.MONTH, month);
        mCalender.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        String selectedDate = DateFormat.getDateInstance(DateFormat.FULL).format(mCalender.getTime());
        tvDate.setText(selectedDate);
    }
}

chevron_right


Output: Run on Emulator


Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Enthusiastic Learner

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


10


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.