Guowei Lv

1 minute read

Let’s see an example of how to do custom layout in compose using Layout(). @Composable fun CustomLayout(modifier: Modifier = Modifier, content: @Composable () -> Unit) { Layout(modifier = modifier, content = content) { measurables, constraints -> var width = 0 var height = 0 val offset = 10.dp.toPx().roundToInt() val placeables = measurables.map { measurable -> measurable.measure(constraints).also { placeable -> width = max(placeable.width, width) height += placeable.height } } layout(width = width + offset * placeables.

Bites of Compose 9

using native Canvas in Compose

Guowei Lv

1 minute read

Let’s see an example of using the Android’s native Canvas in Compose. One of the things that is impossible to do in Compose is doing 3D rotation. Let’s see how to get hold of the native Canvas and do it the old way.

@Composable fun MyView() { val image = ImageBitmap.imageResource(R.drawable.avatar) val paint by remember { mutableStateOf(Paint()) } val animatable = remember { Animatable(0f) } val camera by remember { mutableStateOf(Camera()) } LaunchedEffect(Unit) { animatable.

Bites of Compose 8

rememberCoroutineScope

Guowei Lv

2 minute read

Today’s topic is rememberCoroutineScope. Situation 1 How to launch a Coroutine in Compose? Can we “just do it” ? class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { lifecycleScope.launch { } } } } Answer Apparently, no. Android studio gives an error saying “Calls to launch should happen inside a LaunchedEffect and not composition”. OK, now we know that we shouldn’t do it and how to fix it by using LaunchedEffect.

Bites of Compose 7

All about side effect

Guowei Lv

6 minute read

Let’s talk about side effects in Compose. Situation 1 What will happen when the button is clicked? @Composable fun Test() { var flag by remember { mutableStateOf(false) } Column { Button(onClick = { flag = !flag }) { Text("change") } Text(flag.toString()) Log.d("test", "flag is $flag") } } Answer The Text on the screen will change, also there will be a log entry in logcat. This logging behaviour is something called a side-effect in compose world.

Bites of Compose 6

What is Modifier after all?

Guowei Lv

3 minute read

In previous post we talked about the companion object Modifier and how it’s implementing the interface Modifier. Now it is time to go deeper and see Modifier’s internals. Situation 1 What is Modifier after all? Answer Well, what if I tell you Modifier is just a binary tree data structure. Let’s dive into the source code to prove this. First let’s take a look at the class hierachy, we have 3 pieces: Modifier(interface), Element and CombinedModifier.