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

DatePicker in Kotlin

Using a DatePicker in Kotlin is straightforward, especially with Kotlin's concise syntax and Android KTX (Kotlin extensions) which offer idiomatic and concise Kotlin shortcuts.

Below is an example that demonstrates how to implement a DatePickerDialog in an Android app using Kotlin:

1. Kotlin Code:

import android.app.DatePickerDialog
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.*

class MainActivity : AppCompatActivity() {

    private lateinit var dateTextView: TextView
    private lateinit var pickDateButton: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

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

        pickDateButton.setOnClickListener {
            showDatePickerDialog()
        }
    }

    private fun showDatePickerDialog() {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)

        DatePickerDialog(this,
            { _, selectedYear, selectedMonth, dayOfMonth ->
                dateTextView.text = "${dayOfMonth}/${selectedMonth + 1}/$selectedYear"
            }, year, month, day
        ).show()
    }
}

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

This remains unchanged from the Java example, a layout that consists of a TextView for showing the selected date and a Button to invoke 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:

This Kotlin example mirrors the Java one, but with more concise Kotlin syntax:

  • Lambda expressions replace anonymous classes, providing a cleaner and more compact way to handle button clicks and the date set event.
  • The lateinit keyword is used to delay the initialization of non-null properties.

You can, of course, add further customizations and enhancements, such as setting minimum or maximum dates or integrating with other UI components.

  1. DatePicker example with code in Kotlin:

    • Description: To use DatePicker, add it to your layout XML or create an instance programmatically and handle the date selection event.
    • Code (Layout XML):
      <DatePicker
          android:id="@+id/datePicker"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
      />
      
    • Code (Kotlin):
      val datePicker = findViewById<DatePicker>(R.id.datePicker)
      datePicker.setOnDateChangedListener { _, year, monthOfYear, dayOfMonth ->
          // Handle the selected date
      }
      
  2. Handling date selection events with DatePicker in Kotlin:

    • Description: Implement the OnDateChangedListener interface to handle date selection events when the user picks a date.
    • Code (Kotlin):
      val datePicker = findViewById<DatePicker>(R.id.datePicker)
      datePicker.setOnDateChangedListener { _, year, monthOfYear, dayOfMonth ->
          // Handle the selected date
      }
      
  3. Customizing DatePicker appearance in Kotlin:

    • Description: Customize the appearance of DatePicker programmatically by setting attributes such as text color, background, or other styling options.
    • Code (Kotlin):
      val datePicker = findViewById<DatePicker>(R.id.datePicker)
      datePicker.setBackgroundColor(Color.WHITE)
      datePicker.setTextColor(Color.BLACK)
      // Add more styling attributes as needed
      
  4. Setting default values in DatePicker in Kotlin:

    • Description: You can set default values for the year, month, and day in DatePicker when initializing it.
    • Code (Kotlin):
      val datePicker = findViewById<DatePicker>(R.id.datePicker)
      val defaultYear = 2023
      val defaultMonth = 0 // Months are zero-based (0-11)
      val defaultDay = 1
      datePicker.init(defaultYear, defaultMonth, defaultDay, null)
      
  5. DatePicker vs. DatePickerDialog in Kotlin Android:

    • Description: DatePicker is a widget that can be directly added to layouts, while DatePickerDialog is a dialog that wraps the DatePicker widget. DatePickerDialog is often used when you want to display the date picker as a dialog.
    • Code (Kotlin):
      // Using DatePicker
      val datePicker = findViewById<DatePicker>(R.id.datePicker)
      datePicker.setOnDateChangedListener { _, year, monthOfYear, dayOfMonth ->
          // Handle the selected date
      }
      
      // Using DatePickerDialog
      val currentDate = Calendar.getInstance()
      val datePickerDialog = DatePickerDialog(
          this,
          { _, selectedYear, selectedMonth, selectedDay ->
              // Handle the selected date
          },
          currentDate.get(Calendar.YEAR),
          currentDate.get(Calendar.MONTH),
          currentDate.get(Calendar.DAY_OF_MONTH)
      )
      datePickerDialog.show()
      
  6. Date range restriction with DatePicker in Kotlin:

    • Description: You can restrict the selectable date range by setting minimum and maximum values for the DatePicker.
    • Code (Kotlin):
      val datePicker = findViewById<DatePicker>(R.id.datePicker)
      val currentDate = Calendar.getInstance()
      val minDate = currentDate.timeInMillis
      val maxDate = currentDate.timeInMillis + (365 * 24 * 60 * 60 * 1000) // One year from now
      datePicker.minDate = minDate
      datePicker.maxDate = maxDate
      
  7. Styling and theming DatePicker in Kotlin:

    • Description: You can apply styles and themes to customize the appearance of the DatePicker widget.
    • Code (Styles and Themes - res/values/styles.xml):
      <style name="CustomDatePickerStyle">
          <item name="android:background">#FFFFFF</item>
          <item name="android:textColor">#000000</item>
          <!-- Add more styling attributes as needed -->
      </style>
      
      Code (Kotlin):
      val datePicker = findViewById<DatePicker>(R.id.datePicker)
      datePicker.setBackgroundColor(Color.WHITE)
      datePicker.setTextColor(Color.BLACK)
      // Add more styling attributes as needed