How to use Date Picker Dialog (Kotlin)?
In this tutorial you will learn how to use Date Picker Dialog to pick Date and use it anywhere we want. We will show Date Picker Dialog on a Button click and save the picked date to a TextView.
Step 1: Create a new project OR Open your project
Step 2: Code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:gravity="center"tools:context=".MainActivity"><Buttonandroid:id="@+id/pickDateBtn"android:text="Pick Date"android:layout_width="wrap_content"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/dateTv"android:text="Date"android:textSize="30sp"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>
MainActivity.kt
package com.blogspot.devofandroid.kotlinpracticeimport android.app.DatePickerDialogimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport java.util.*class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val mPickTimeBtn = findViewById<Button>(R.id.pickDateBtn)val textView = findViewById<TextView>(R.id.dateTv)val c = Calendar.getInstance()val year = c.get(Calendar.YEAR)val month = c.get(Calendar.MONTH)val day = c.get(Calendar.DAY_OF_MONTH)mPickTimeBtn.setOnClickListener {val dpd = DatePickerDialog(this , DatePickerDialog.OnDateSetListener { view , year , monthOfYear , dayOfMonth ->// Display Selected date in TextViewtextView.setText("" + dayOfMonth + " " + month + " , " + year)} , year , month , day)dpd.show()}}}
0 Response to "Date Picker Obrolan (Kotlin) - Android Studio"