Skip to content

Commit

Permalink
Change implementation of Timer to Handler
Browse files Browse the repository at this point in the history
  • Loading branch information
hendrawd committed Jan 8, 2018
1 parent 5fe4aa7 commit 9779408
Showing 1 changed file with 19 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,9 @@

package id.co.ionsoft.randomnumberanimationlibrary

import android.os.Handler
import android.widget.TextView
import org.jetbrains.anko.runOnUiThread
import java.security.SecureRandom
import java.util.*

/**
* Create random number animation from a TextView
Expand All @@ -36,7 +35,15 @@ import java.util.*
class RandomNumberAnimation(private val textView: TextView) {

private val random = SecureRandom()
private var timer: Timer? = null
private val handler = Handler()
private val runnable = object : Runnable {
override fun run() {
textView.text = randomize(textView.text)
handler.postDelayed(this, delay)
}
}
private var delay = 16L
private var started = false
private var defaultValue: CharSequence = textView.text

/**
Expand Down Expand Up @@ -65,29 +72,22 @@ class RandomNumberAnimation(private val textView: TextView) {
* Stop the animation
*/
fun stop(keepChange: Boolean = false) {
timer?.cancel()
timer = null
if (!keepChange) {
textView.text = defaultValue
if (started) {
handler.removeCallbacks(runnable)
started = false
if (!keepChange) {
textView.text = defaultValue
}
}
}

/**
* Start the animation
*/
fun start() {
if (timer != null) {
stop()
if (!started) {
handler.postDelayed(runnable, delay)
started = true
}
timer = Timer()
timer!!.schedule(object : TimerTask() {
override fun run() {
textView.context.runOnUiThread({
if (timer != null) {
textView.text = randomize(textView.text)
}
})
}
}, 1, 16) // 1000 / 16 = 62.5FPS
}
}

0 comments on commit 9779408

Please sign in to comment.