Jetpack Compose

Bites of Compose 11

LookAheadLayout

Guowei Lv

1 minute read

Let’s see an example of how to use LookAheadLayout to implement shared view transition animation. Here is the code: @Composable fun Avatar(modifier: Modifier = Modifier) { Box( modifier = modifier .size(100.dp) .background(Color.Green) ) } @OptIn(ExperimentalComposeUiApi::class) @Composable fun CustomLookAheadLayout3() { var flag by remember { mutableStateOf(false) } var lookaheadOffset by remember { mutableStateOf(Offset.Zero) } val lookaheadOffsetAnim by animateOffsetAsState( targetValue = lookaheadOffset, animationSpec = TweenSpec(durationMillis = 500), label = "" ) val sharedView = remember { movableContentOf { Avatar( modifier = Modifier .

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.