Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

DatePickerDialog in Android

The DatePickerDialog is a UI component that allows users to pick a date via a simple and user-friendly interface. It��s usually presented when the user taps on an input field that requires a date value.

Let's walk through an example of how to use DatePickerDialog in Android:

1. Java Code:

Here��s how you might create a DatePickerDialog in an Activity:

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    private TextView dateTextView;
    private Button pickDateButton;

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

        dateTextView = findViewById(R.id.dateTextView);
        pickDateButton = findViewById(R.id.pickDateButton);

        pickDateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog();
            }
        });
    }

    private void showDatePickerDialog() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                MainActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        dateTextView.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
                    }
                }, year, month, day);
        datePickerDialog.show();
    }
}

2. XML Layout (res/layout/activity_main.xml):

This is a simple layout that contains a TextView to display the selected date and a Button to trigger the DatePickerDialog.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/dateTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Selected Date Here"
        android:textSize="18sp" />

    <Button
        android:id="@+id/pickDateButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pick a Date" />

</LinearLayout>

Explanation:

  • When the user taps on the pickDateButton, the showDatePickerDialog() method is invoked.
  • Inside showDatePickerDialog(), the current year, month, and day are retrieved.
  • A DatePickerDialog instance is then created with the current date pre-selected. When a date is selected by the user, the onDateSet method of the OnDateSetListener is called, and the selected date is displayed in the dateTextView.

This is a basic implementation. You can further customize the DatePickerDialog to match your needs, such as setting a minimum and maximum date or styling it differently.

  1. DatePickerDialog example with code in Android:

    • Description: To use DatePickerDialog, create an instance of it, set its listener, and show the dialog when needed.
    • Code (Kotlin):
      val currentDate = Calendar.getInstance()
      val year = currentDate.get(Calendar.YEAR)
      val month = currentDate.get(Calendar.MONTH)
      val day = currentDate.get(Calendar.DAY_OF_MONTH)
      
      val datePicker = DatePickerDialog(
          this,
          { _, selectedYear, selectedMonth, selectedDay ->
              // Handle the selected date
              val selectedDate = Calendar.getInstance()
              selectedDate.set(selectedYear, selectedMonth, selectedDay)
              // Use selectedDate as needed
          },
          year,
          month,
          day
      )
      datePicker.show()
      
  2. Customizing DatePickerDialog appearance in Android:

    • Description: You can customize the appearance of DatePickerDialog by setting additional properties like the title, cancelable behavior, or using a custom layout.
    • Code (Kotlin):
      val datePicker = DatePickerDialog(
          this,
          R.style.CustomDatePickerStyle, // Set custom style
          { _, selectedYear, selectedMonth, selectedDay ->
              // Handle the selected date
          },
          year,
          month,
          day
      )
      datePicker.setTitle("Pick a Date") // Set custom title
      datePicker.setCancelable(false) // Make it non-cancelable
      datePicker.show()
      
  3. Handling date selection events with DatePickerDialog:

    • Description: Implement the OnDateSetListener interface to handle the date selection event when the user picks a date.
    • Code (Kotlin):
      val datePicker = DatePickerDialog(
          this,
          { _, selectedYear, selectedMonth, selectedDay ->
              // Handle the selected date
          },
          year,
          month,
          day
      )
      datePicker.show()
      
  4. Setting default values in DatePickerDialog in Android:

    • Description: You can set default values for the year, month, and day when showing the DatePickerDialog.
    • Code (Kotlin):
      val datePicker = DatePickerDialog(
          this,
          { _, selectedYear, selectedMonth, selectedDay ->
              // Handle the selected date
          },
          defaultYear,
          defaultMonth,
          defaultDay
      )
      datePicker.show()
      
  5. DatePickerDialog vs. DatePicker in Android:

    • Description: DatePickerDialog is a dialog that wraps the DatePicker widget. It provides a user-friendly interface for selecting dates, while DatePicker is a standalone widget.
    • Code (Kotlin):
      // Using DatePickerDialog
      val datePickerDialog = DatePickerDialog(this, /* ... */)
      datePickerDialog.show()
      
      // Using DatePicker directly in a layout XML
      <DatePicker
          android:id="@+id/datePicker"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:calendarViewShown="false"
      />
      
  6. Date range restriction with DatePickerDialog:

    • Description: You can restrict the selectable date range by setting minimum and maximum values for the DatePickerDialog.
    • Code (Kotlin):
      val datePicker = DatePickerDialog(
          this,
          { _, selectedYear, selectedMonth, selectedDay ->
              // Handle the selected date
          },
          year,
          month,
          day
      )
      val minDate = Calendar.getInstance()
      minDate.set(2022, Calendar.JANUARY, 1)
      val maxDate = Calendar.getInstance()
      maxDate.set(2022, Calendar.DECEMBER, 31)
      datePicker.datePicker.minDate = minDate.timeInMillis
      datePicker.datePicker.maxDate = maxDate.timeInMillis
      datePicker.show()
      
  7. Styling and theming DatePickerDialog in Android:

    • Description: You can apply styles and themes to customize the appearance of the DatePickerDialog.
    • Code (Styles and Themes - res/values/styles.xml):
      <style name="CustomDatePickerStyle" parent="Theme.AppCompat.Light.Dialog">
          <item name="colorAccent">@color/colorAccent</item>
          <!-- Add more styling attributes as needed -->
      </style>
      
      Code (Kotlin):
      val datePicker = DatePickerDialog(
          this,
          R.style.CustomDatePickerStyle,
          { _, selectedYear, selectedMonth, selectedDay ->
              // Handle the selected date
          },
          year,
          month,
          day
      )
      datePicker.show()