Wednesday, April 14, 2021

jetpack compose - AnimateColorAsState duration

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        val isLighter = remember { mutableStateOf(true) }
        val isEnabled = remember { mutableStateOf(true) }

        val color = animateColorAsState(
            targetValue = if (isLighter.value)
                Color(0xFFE3DAC9) else Color(0xFFFF0800),

            animationSpec = tween(
                durationMillis = 5000 // 5 seconds duration
            ),
            finishedListener = {
                // disable the button
                isEnabled.value = true
            }
        )

        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Color(0xFFE1A95F))
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Button(
                onClick = {
                    isLighter.value = !isLighter.value
                    isEnabled.value = false
                },
                colors = ButtonDefaults.buttonColors(
                    Color(0xFF16161D), Color(0xCCFFFFFF)
                ),
                enabled = isEnabled.value
            ) {
                Text(
                    text = "Animate Color Change",
                    modifier = Modifier.padding(12.dp)
                )
            }

            Icon(
                Icons.Filled.Favorite,
                contentDescription = "Localized description",
                Modifier.size(300.dp),
                tint = color.value
            )
        }
    }



    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}