Search code examples
androidkotlinanimationandroid-jetpack-composeandroid-drawable

Replace AnimationDrawable by using jetPack Compose Image


I want to replace my view which I created in xml with the Jetpack Compose API.

But now I am stuck on replacing my AnimationDrawable.

I use it to make a "Charging Animation" by start a Transistion of 3 images (low battery, mid battery and full battery image)

So when phone is charging I start the animation by calling a TimerTask to start the Animation infinite until the phone is disconnected from power source.

private class MyTimerTask(private val transitionDrawable: AnimationDrawable) : TimerTask() {
    override fun run() {
        Dispatcher.runOnUiThread {
            transitionDrawable.start()
        }
    }
}

init {
    drawLow = AppCompatResources.getDrawable(context, R.mipmap.low_battery)
    drawMid = AppCompatResources.getDrawable(context, R.mipmap.mid_battery)
    drawFull = AppCompatResources.getDrawable(context, R.mipmap.full_battery)

    if (drawLow !== null && drawMid != null && drawFull != null) {
        mTransitionDrawable.addFrame(drawLow, 500)
        mTransitionDrawable.addFrame(drawMid, 500)
        mTransitionDrawable.addFrame(drawFull, 500)
    }
}

How do I do it with the compose API? I have to convert the png files to ImageBitmap. So I cannot use the AnimationDrawable anymore.

((ResourcesCompat.getDrawable(context.resources, R.mipmap.low_battery, context.theme) as BitmapDrawable).bitmap).asImageBitmap()

So what can I do to achieve the "charging animation"?


Solution

  • 1、build.gradle Configure the useSupportLibrary property:

    android {
        compileSdk 31
    
        defaultConfig {
            applicationId "com.your.package.xxxx"
            minSdk 21
            targetSdk 31
            versionCode 1
            versionName "1.0"
    
            vectorDrawables {
                useSupportLibrary true
            }
        }
    }
    

    2、dependencies

    implementation "com.google.accompanist:accompanist-drawablepainter:0.28.0"
    

    3、Display:

    val animationDrawable = AnimationDrawable()
    //add your images in animationDrawable by giving information of duration etc like you gave in xml file..
    Image(
        painter = rememberDrawablePainter(animationDrawable),
        contentDescription = null,
        modifier = Modifier.wrapContentSize(), 
        contentScale = ContentScale.Crop
    )
    
    animationDrawable?.start()