Monday, February 19, 2018

android kotlin - DatePicker example

MainActivity.kt

package com.cfsuman.kotlinexamples

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.DatePicker
import kotlinx.android.synthetic.main.activity_main.*
import android.widget.Toast
import java.text.DateFormat
import java.util.Random
import java.util.Calendar


class MainActivity : AppCompatActivity() {

    private lateinit var calendar:Calendar

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

        // Initialize a new calendar instance
        calendar = Calendar.getInstance()

        // Get the Calendar current year, month and day of month
        val thisYear = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)

        // Initialize the date picker widget with system current date
        date_picker.init(
                thisYear,
                month,
                day,
                DatePicker.OnDateChangedListener {view, year, monthOfYear, dayOfMonth ->
                    // Do something when the date changed in date picker object

                    // Display the date picker selected date on text view
                    text_view.text = "Date Changed : ${formatDate(year,monthOfYear,dayOfMonth)}"
            }
        )


        // Set a click listener for set date button widget
        button_set.setOnClickListener{
            // Update the date picker data by a random date
            val year = randomInRange(2000,2025)
            val month = randomInRange(0,11)
            val day = randomInRange(0,27)

            // Update the date picker with random date
            date_picker.updateDate(
                    year, // Year
                    month, // The month which is starting from zero.
                    day // Day of month
            )

            // Toast the new date
            Toast.makeText(
                    applicationContext,
                    "Set Date : ${formatDate(year,month,day)}",
                    Toast.LENGTH_SHORT).show()

        }


        // Set a click listener for get date button widget
        button_get.setOnClickListener{
            // Get the date picker widget selected date
            val selectedDate = formatDate(date_picker.year,date_picker.month,date_picker.dayOfMonth)
            // Display the date picker selected formatted date
            text_view.text = "Selected Date : $selectedDate"
        }
    }



    // Custom method to format date
    private fun formatDate(year:Int, month:Int, day:Int):String{
        // Create a Date variable/object with user chosen date
        calendar.set(year, month, day, 0, 0, 0)
        val chosenDate = calendar.time

        // Format the date picker selected date
        val df = DateFormat.getDateInstance(DateFormat.MEDIUM)
        return df.format(chosenDate)
    }


    // 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="#dce9d9"
    >
    <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"
        />
    <DatePicker
        android:id="@+id/date_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:datePickerMode="spinner"
        android:calendarViewShown="false"
        />
    <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 Date"
            />
        <Button
            android:id="@+id/button_set"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Set Date"
            />
    </LinearLayout>
</LinearLayout>