AnimationDrawable自定义

mac2026-06-10  13

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) } }
最新回复(0)