DatePicker in Kotlin

Android DatePicker is a user interface control that allows us to select a date by day, month, and year in our Android application. DatePicker is used to guarantee that users select the correct date.

In this article, you will learn how to create your DatePicker widget in Flutter. So let’s take DatePickerexample of the Table  in Android of Mobile application.

                                               
Syntax
 <DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="calendar"/>
Step-by-Step Implementation 

Step 1: Create a New Project in Android Studio (File >new  project). 


Step 2: Create an activity_main.xml file in your layout folder . path (res>layout)

Implement the same in​voke the following code inside activity_main.xml file. 

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.491"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Create an MainActivity.kt file in your package folder .

Implement the same invoke the fol​lowing code inside MainActivity.kt file.

 import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.DatePicker
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.util.Calendar

class MainActivity : AppCompatActivity() {
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val datePicker = findViewById<DatePicker>(R.id.date_Picker)
val today = Calendar.getInstance()
datePicker.init(
today.get(Calendar.YEAR), today.get(Calendar.MONTH),
today.get(Calendar.DAY_OF_MONTH)

) { view, year, month, day ->
val month = month + 1
val msg = "You Selected: $day/$month/$year"
Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
}
}
}
Step 4 : Output of above example

                                                 

Happy coding!

365Bloggy July 10, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive