Time Picker Dialog (Kotlin) - Android Studio
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"> <Button android:id="@+id/pickTimeBtn" android:text="Pick Time" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android: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.kotlinpractice import android.app.TimePickerDialog import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView import java.text.SimpleDateFormat import 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() } } }
Comments
Post a Comment