1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.deskclock 18 19 import android.text.format.DateUtils 20 import android.widget.TextView 21 22 import com.android.deskclock.uidata.UiDataModel 23 24 /** 25 * A controller which will format a provided time in millis to display as a stopwatch. 26 */ 27 class StopwatchTextController( 28 private val mMainTextView: TextView, 29 private val mHundredthsTextView: TextView 30 ) { 31 private var mLastTime = Long.MIN_VALUE 32 setTimeStringnull33 fun setTimeString(accumulatedTime: Long) { 34 // Since time is only displayed to centiseconds, if there is a change at the milliseconds 35 // level but not the centiseconds level, we can avoid unnecessary work. 36 if (mLastTime / 10 == accumulatedTime / 10) { 37 return 38 } 39 40 val hours = (accumulatedTime / DateUtils.HOUR_IN_MILLIS).toInt() 41 var remainder = (accumulatedTime % DateUtils.HOUR_IN_MILLIS).toInt() 42 43 val minutes = (remainder / DateUtils.MINUTE_IN_MILLIS).toInt() 44 remainder = (remainder % DateUtils.MINUTE_IN_MILLIS).toInt() 45 46 val seconds = (remainder / DateUtils.SECOND_IN_MILLIS).toInt() 47 remainder = (remainder % DateUtils.SECOND_IN_MILLIS).toInt() 48 49 mHundredthsTextView.text = UiDataModel.uiDataModel.getFormattedNumber(remainder / 10, 2) 50 51 // Avoid unnecessary computations and garbage creation if seconds have not changed since 52 // last layout pass. 53 if (mLastTime / DateUtils.SECOND_IN_MILLIS != 54 accumulatedTime / DateUtils.SECOND_IN_MILLIS) { 55 val context = mMainTextView.context 56 val time = Utils.getTimeString(context, hours, minutes, seconds) 57 mMainTextView.text = time 58 } 59 mLastTime = accumulatedTime 60 } 61 }