Jetpack Compose

Bites of Compose 16

Animatable

Guowei Lv

1 minute read

In previous post we talked about how to do animation in Compose using animateXXXAsState() function. And also see that though easy to use, it has limited customization capabilities. Now, let’s take a look at a lower level(and more powerful) way: Animatable. @Composable fun AnimatableDemo() { val coroutineScope = rememberCoroutineScope() val anim = remember { Animatable(48.dp, Dp.VectorConverter) } Box( modifier = Modifier .size(anim.value) .background(Color.Green) .clickable { coroutineScope.launch { val current = anim.

Bites of Compose 15

animateXXXAsState()

Guowei Lv

2 minute read

Let’s take a look at the simplest way to implement animation in Compose, which is using animateXXXAsState() set of functions. Let’s say we want to increase the size of a Box by 10.dp every time we click on it. We already know how to do it without animation: @Preview @Composable fun AnimationDemo() { var target by remember { mutableStateOf(48.dp) } Box( modifier = Modifier .size(target) .background(Color.Green) .clickable { target += 10.

Bites of Compose 14

Mental model of LayoutModifier + DrawModifier

Guowei Lv

1 minute read

In previous post, we discussed the mental model of multiple LayoutModifiers. Now let’s talk about the mental model of the combination of LayoutModifier and DrawModifier. First of all, we need to know that everything on screen is drawn using some DrawModifier: Text, Image, Background, etc. Let me give you the mental model directly. Given the following code: Modifier.drawModifier1().drawModifier2().drawModifier3().layoutModifier1() .drawModifier4().drawModifier5().layoutModifier2() .drawModifier6().layoutModifier3() The model is: Notice that the modifiers are always attached to its nearest LayoutModifier on the right.

Bites of Compose 13

Mental model of LayoutModifier

Guowei Lv

2 minute read

When we have multiple LayoutModifiers, how do we think about them? In this post, I will introduce a useful mental model. First we need to understand that LayoutModifier determines size and position of a component. The model is simple, let’s say we have the following code: Text( text = "Hello", modifier = Modifier .padding(20.dp) .background(Color.Green) // ignore this for now, only for understanding purpose .size(50.dp) ) We can think of this as:

Bites of Compose 12

Use LayoutModifier to implement padding

Guowei Lv

2 minute read

LayoutModifier is a very important type of Modifier in Compose. It can decorate its component’s layout. So let’s get an idea of what this means by implementing padding using it. Let’s try to add a 10dp padding around a Text. class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LayoutModifierPadding() } } } @Composable fun LayoutModifierPadding() { Box( modifier = Modifier .size(100.dp) .background(Color.LightGray) ) { Text( "Hello!