Untitled
unknown
plain_text
9 months ago
3.1 kB
3
Indexable
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private var timerTextView: TextView? = null
private var historyTextView: TextView? = null
private var startButton: Button? = null
private var stopButton: Button? = null
private var countDownTimer: CountDownTimer? = null
private var isTimerRunning = false
private var timeLeftInMillis: Long = 30000 // 30 seconds
private val timerHistory: MutableList<String> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
timerTextView = findViewById<TextView>(R.id.timerTextView)
historyTextView = findViewById<TextView>(R.id.historyTextView)
startButton = findViewById(R.id.startButton)
stopButton = findViewById<Button>(R.id.stopButton)
updateTimerText()
startButton!!.setOnClickListener {
if (!isTimerRunning) {
startTimer()
}
}
stopButton!!.setOnClickListener {
if (isTimerRunning) {
stopTimer()
}
}
}
private fun startTimer() {
countDownTimer = object : CountDownTimer(timeLeftInMillis, 1000) {
override fun onTick(millisUntilFinished: Long) {
timeLeftInMillis = millisUntilFinished
updateTimerText()
}
override fun onFinish() {
isTimerRunning = false
timerHistory.add(formatTime(30000 - timeLeftInMillis) + " seconds")
if (timerHistory.size > 5) {
timerHistory.removeAt(0)
}
updateHistoryText()
resetTimer()
}
}.start()
isTimerRunning = true
}
private fun stopTimer() {
countDownTimer!!.cancel()
isTimerRunning = false
timerHistory.add(formatTime(30000 - timeLeftInMillis) + " seconds (stopped)")
if (timerHistory.size > 5) {
timerHistory.removeAt(0)
}
updateHistoryText()
resetTimer()
}
private fun resetTimer() {
timeLeftInMillis = 30000 // Reset to 30 seconds
updateTimerText()
}
private fun updateTimerText() {
val seconds = (timeLeftInMillis / 1000).toInt()
timerTextView!!.text = String.format("%02d", seconds)
}
private fun updateHistoryText() {
val history = StringBuilder("Last 5 Timers:\n")
for (entry in timerHistory) {
history.append(entry).append("\n")
}
historyTextView!!.text = history.toString()
}
private fun formatTime(millis: Long): String {
return (millis / 1000).toString()
}
}Editor is loading...
Leave a Comment