Last active
April 17, 2021 16:25
-
-
Save abircse/63b6078689f87b33e4c5bce4dc9be695 to your computer and use it in GitHub Desktop.
CountDownTimer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Simple Date Format | |
val dateformat = SimpleDateFormat("hh:mm:ss",Locale.getDefault()) | |
// Get Current time like dateformat above | |
val currentTime = dateformat.format(Date()) | |
// Counter Endtime with Second | |
val endTime = "10:30:00" | |
// Format time as Parse to Milisecond for run counter | |
val ctime = dateformat.parse(currentTime) | |
val eDate = dateformat.parse(endTime) | |
//How much milliseconds need to run counter (result from current time vs end time) | |
val result = eDate.time - ctime.time | |
// Counter Interval time in Second (e.g 1000milisecond = 1 second) | |
val interval = 1000 | |
// Run Timer | |
val timer = object: CountDownTimer(result, interval) { | |
override fun onTick(millisUntilFinished: Long) { | |
val textview = findViewById<TextView>(R.id.text) | |
var diff = millisUntilFinished | |
val secondsInMilli: Long = 1000 | |
val minutesInMilli = secondsInMilli * 60 | |
val hoursInMilli = minutesInMilli * 60 | |
val elapsedHours = diff / hoursInMilli | |
diff %= hoursInMilli | |
val elapsedMinutes = diff / minutesInMilli | |
diff %= minutesInMilli | |
val elapsedSeconds = diff / secondsInMilli | |
// Set Runtime Result to Text View | |
textview.text = "$elapsedHours hour $elapsedMinutes minute $elapsedSeconds second" | |
} | |
override fun onFinish() { | |
// Toast When Counter Finished | |
Toast.makeText(this@MainActivity, "Counter finish", Toast.LENGTH_SHORT).show() | |
} | |
} | |
timer.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment