From febb166894ae68efc67a6fc2df8e88999004bf1e Mon Sep 17 00:00:00 2001 From: tibbi Date: Wed, 28 Feb 2018 16:08:57 +0100 Subject: [PATCH] update the clock time every second --- .../clock/fragments/ClockFragment.kt | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/app/src/main/kotlin/com/simplemobiletools/clock/fragments/ClockFragment.kt b/app/src/main/kotlin/com/simplemobiletools/clock/fragments/ClockFragment.kt index e014afe0..f086bc1a 100644 --- a/app/src/main/kotlin/com/simplemobiletools/clock/fragments/ClockFragment.kt +++ b/app/src/main/kotlin/com/simplemobiletools/clock/fragments/ClockFragment.kt @@ -1,14 +1,42 @@ package com.simplemobiletools.clock.fragments import android.content.Context +import android.os.Handler import android.util.AttributeSet import android.widget.RelativeLayout import com.simplemobiletools.commons.extensions.updateTextColors import kotlinx.android.synthetic.main.fragment_clock.view.* +import java.util.* class ClockFragment(context: Context, attributeSet: AttributeSet) : RelativeLayout(context, attributeSet) { + private val ONE_SECOND = 1000L + private var passedSeconds = 0 + + private val updateHandler = Handler() + override fun onFinishInflate() { super.onFinishInflate() context.updateTextColors(clock_fragment) + val offset = Calendar.getInstance().timeZone.rawOffset + passedSeconds = ((Calendar.getInstance().timeInMillis + offset) / 1000).toInt() + updateCurrentTime() + } + + private fun updateCurrentTime() { + val hours = (passedSeconds / 3600) % 24 + val minutes = (passedSeconds / 60) % 60 + val seconds = passedSeconds % 60 + val format = "%02d:%02d:%02d" + clock_time.text = String.format(format, hours, minutes, seconds) + + updateHandler.postDelayed({ + passedSeconds++ + updateCurrentTime() + }, ONE_SECOND) + } + + override fun onDetachedFromWindow() { + super.onDetachedFromWindow() + updateHandler.removeCallbacksAndMessages(null) } }