How to use Time Picker Dialog (Kotlin)?
In this tutorial how to use Time Picker Dialog in Kotlin using Android Studio. We will create a Button(to click to) to show Time Picker Dialog. The picked time will be displayed in 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/pickTimeBtn"android:text="Pick Time"android:layout_width="wrap_content"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/timeTv"android:text="Time"android:textSize="30sp"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout>
MainActivity.kt
package com.blogspot.devofandroid.kotlinpracticeimport android.app.TimePickerDialogimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.TextViewimport java.text.SimpleDateFormatimport java.util.*class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val mPickTimeBtn = findViewById<Button>(R.id.pickTimeBtn)val textView = findViewById<TextView>(R.id.timeTv)mPickTimeBtn.setOnClickListener {val cal = Calendar.getInstance()val timeSetListener = TimePickerDialog.OnTimeSetListener { timePicker , hour , minute ->cal.set(Calendar.HOUR_OF_DAY , hour)cal.set(Calendar.MINUTE , minute)textView.text = SimpleDateFormat("HH:mm").format(cal.time)}TimePickerDialog(this , timeSetListener , cal.get(Calendar.HOUR_OF_DAY) , cal.get(Calendar.MINUTE) , true).show()}}}
0 Response to "Time Picker Obrolan (Kotlin) - Android Studio"