Sunday, February 18, 2018

android kotlin - TimePicker example

MainActivity.kt

package com.cfsuman.kotlinexamples

import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.widget.TimePicker
import java.util.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Set a time change listener for time picker widget
        time_picker.setOnTimeChangedListener{
            view,hourOfDay,minute->
            text_view.text = "Time(HH:MM) ${getHourAMPM(hourOfDay)} " +
                    ": $minute ${getAMPM(hourOfDay)}"
        }


        // Set a click listener for set time button widget
        button_set.setOnClickListener{
            // Set a random time
            setPickerTime(time_picker)
        }


        // Set a click listener for get time button widget
        button_get.setOnClickListener{
            // Display the picker current time on text view
            text_view.text = "Time(HH:MM) ${getPickerTime(time_picker)}"
        }


        // Set a click listener for toggle 24 button widget
        button_toggle_24.setOnClickListener{
            if(time_picker.is24HourView){
                time_picker.setIs24HourView(false)
            }else{
                time_picker.setIs24HourView(true)
            }
        }
    }



    // Custom method to get time picker current time as string
    private fun getPickerTime(timePicker: TimePicker):String{
        val hour = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            timePicker.hour
        } else {
            timePicker.currentHour
        }

        val minute = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            timePicker.minute
        }else{
            timePicker.currentMinute
        }

       return "${getHourAMPM(hour)} : $minute ${getAMPM(hour)}"
    }


    // Custom method to get AM PM value from provided hour
    private fun getAMPM(hour:Int):String{
        return if(hour>11)"PM" else "AM"
    }


    // Custom method to get hour for AM PM time format
    private fun getHourAMPM(hour:Int):Int{
        // Return the hour value for AM PM time format
        var modifiedHour = if (hour>11)hour-12 else hour
        if (modifiedHour == 0){modifiedHour = 12}
        return modifiedHour
    }


    // Custom method to set time picker time
    private fun setPickerTime(timePicker: TimePicker){
        // Get random time
        val hour = randomInRange(0,23)
        val minute = randomInRange(0,59)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            timePicker.hour = hour
            timePicker.minute = minute
        }else{
            timePicker.currentHour = hour
            timePicker.currentMinute = minute
        }
    }


    // Custom method to get a random number from the provided range
    private fun randomInRange(min:Int, max:Int):Int{
        //define a new Random class
        val r = Random()

        //get the next random number within range
        // Including both minimum and maximum number
        return r.nextInt((max - min) + 1) + min;
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:background="#f8fdff"
    >
    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="25dp"
        android:padding="25dp"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
        android:textColor="#ff0000"
        />
    <TimePicker
        android:id="@+id/time_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:timePickerMode="spinner"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <Button
            android:id="@+id/button_get"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Get Time"
            />
        <Button
            android:id="@+id/button_set"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Set Time"
            />
        <Button
            android:id="@+id/button_toggle_24"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Toggle 24"
            />
    </LinearLayout>
</LinearLayout>