AnimationDrawable自定義

import android.graphics.drawable.AnimationDrawable
import android.graphics.drawable.Drawable
import android.os.Handler
import android.util.Log

class FlashAnimationDrawable : AnimationDrawable() {
    private val runnable: Runnable
    private val handler: Handler = Handler()
    private var onFrameChangedListener: OnFrameChangedListener? = null
    private var minDuration: Int = Int.MAX_VALUE
    private var lastDrawable: Drawable? = null
    private var drawableIndexMap: HashMap<Drawable, Int> = HashMap()

    init {
        runnable = Runnable {
            Log.d("FlashDebug", "run is called.")
            if(current != null && lastDrawable != current){
                onFrameChangedListener?.onFrameChanged(drawableIndexMap[current]?:0)
                lastDrawable = current
            }
            resetHandler()
        }
    }

    private fun initAnimation(){
        for (i in 0 until this.numberOfFrames) {
            drawableIndexMap[getFrame(i)] = i
            if (minDuration > getDuration(i)) {
                minDuration = getDuration(i)
            }
        }
    }

    private fun resetHandler() {
        Log.d("FlashDebug", "minDuration="+minDuration)
        handler.postDelayed(runnable, minDuration.toLong())
    }

    override fun start() {
        super.start()
        initAnimation()
        Log.d("FlashDebug", "start is called")
        resetHandler()
    }

    override fun stop() {
        super.stop()
        Log.d("FlashDebug", "stop is called.")
        handler.removeCallbacks(runnable)
        drawableIndexMap.clear()
    }

    fun setOnFrameChangedListener(onFrameChangedListener: OnFrameChangedListener){
        this.onFrameChangedListener = onFrameChangedListener
    }

    interface OnFrameChangedListener{
        fun onFrameChanged(frameId: Int)
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章