Dynamic TimePicker in Kotlin
Android TimePicker is a user interface control for selecting the time in either 24-hour format or AM/PM mode. It is used to ensure that users pick a valid time for the day in our application.
In android, TimePicker is available in two modes first one is clock mode and another one is spinner mode. In this article, we should create TimePicker widget programmatically in Kotlin file.
First we create a new project by following the below steps:
- Click on File, then New => New Project.
- After that include the Kotlin support and click on next.
- Select the minimum SDK as per convenience and click next button.
- Then select the Empty activity => next => finish.
Modify activity_main.xml file
In this file, we use the LinearLayout inside the RelativeLayout, which is going to be accessed in the Kotlin file. Also set the attribute of the Layout like id, orientation etc.
Update strings.xml file
Here, we update the name of the application using the string tag.
Create TimePicker in MainActivity.kt file
First, we declare two variables txtView and timePicker to create the widgets.
val txtView = TextView(this) val timePicker = TimePicker(this)
then, we should add them into the Linearlayout using
val linearLayout = findViewById
(R.id.linear_layout) linearLayout?.addView(timePicker) linearLayout?.addView(txtView)
How to display time and its Logic already covered in previous topic.
Run as Emulator:
We can change the view by clicking on the icon in left bottom. To use text TimePicker click on keyboard icon and to use the Clock we should click on the clock icon.