DEV Community

Cover image for Animating Composables Made Easy
Isaac Akakpo
Isaac Akakpo

Posted on • Updated on

Animating Composables Made Easy

Animations in android hasn't always been straight forward to implement. The introduction of jetpack compose makes animations a bit more enjoyable and easier to implement.

In this article we'll be looking at the animateValueAsState api. Values currently supported are Color,Float,Dp,Rect,Int,Inoffset and Instize.

Let's take a look at animating color states for this series. We'll be creating something like this

Image description


// --> 1

val Purple = Color(0xFF6200EE)
val Orange = Color(0xFFFF5722)
val White =  Color(0xFFFFFFFF)
val Blue =  Color(0xFF4052B8)
val Green =  Color(0xFF4CAF50)
val Yellow =  Color(0xFFFFEB3B)



// --> 2
 var currentColor by remember {
        mutableStateOf(White)
    }

// --> 3
    val colors by remember {
        mutableStateOf(listOf(White, Orange, Purple200, Blue, Green,Yellow))
    }

val cardBackground by animateColorAsState(targetValue = currentColor)


    Box(modifier = Modifier.fillMaxSize()) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(10.dp)
                .height(200.dp),
            onClick = { 
                // --> 4
                currentColor = colors.random()
             },
            backgroundColor = cardBackground,
            elevation = 3.dp, indication = rememberRipple()
        ) {
            Box(modifier = Modifier.fillMaxSize()) {
                Text(text = "Click to Change Color", modifier = Modifier.align(Alignment.Center))
            }
        }

    }
Enter fullscreen mode Exit fullscreen mode
  1. We declare the colors we want to set the box as we click it.
  2. Animate*AsState requires a target state that is mutable. NB : Animate*AsState in it self needs immutable
  3. Make a list from all defined colors
  4. Assign currentColor a new value on click

Happy Coding, See you in the next series !
Code Link

Latest comments (0)