Wednesday, April 14, 2021

jetpack compose - AnimateColorAsState

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.foundation.shape.CircleShape
import androidx.compose.material.*
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.draw.clip
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 color = animateColorAsState(
            targetValue = if (isLighter.value)
                Color.LightGray else Color(0xFFE63E62),

            animationSpec = spring(
                dampingRatio = Spring.DampingRatioNoBouncy,
                stiffness = Spring.StiffnessVeryLow
            ),
            finishedListener = {
                // do something here
            }
        )

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

            Box(
                modifier = Modifier
                    .clip(CircleShape)
                    .background(color.value)
                    .padding(16.dp)
                    .fillMaxWidth()
                    .height(350.dp)
            )
        }
    }



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