@Composable
fun Greeting(name: String) { Text("Hello, $name") }CompositionLocal 与 CompositionLocalProvider 覆盖提供LocalContext.current、LocalDensity.current、LocalLayoutDirectionval LocalGreeting = staticCompositionLocalOf { "Hi" }
@Composable fun Banner() {
CompositionLocalProvider(LocalGreeting provides "你好") {
Text(LocalGreeting.current)
}
}rememberSaveable + Saver 自定义序列化保存跨重建var s by remember { mutableStateOf(0) };rememberSaveable 跨重建val even by remember { derivedStateOf { s % 2 == 0 } }mutableIntStateOf/mutableLongStateOf(减少装箱)val current by rememberUpdatedState(value) 避免闭包陈旧mutableStateListOf/mutableStateMapOf 或 SnapshotStateListremember(key1, key2) { ... } 键变化即重建记忆值derivedStateOf 缓存并延迟计算(按需)@Immutable/@StablecollectAsStateWithLifecycle()(见“Lifecycle”卡)LaunchedEffect(key) { /* suspend work */ }DisposableEffect(key) { onDispose{ /* clean */ } }snapshotFlow { state } 转 Flow 并收集val scope = rememberCoroutineScope() 触发事件SideEffect { /* commit to UI tree */ }produceState(initial) { /* emit via value= */ }LaunchedEffect(Unit);依赖改变即重启副作用@Composable
fun UserPanel(vm: VM){
val user by produceState(null) {
value = runCatching { vm.load() }.getOrNull()
}
user?.let { Text(it.name) }
} Modifier.padding/size/fillMaxWidth/weightArrangement.* 与 Alignment.* 组合Layout{{ measurables, constraints -> /* measure/place */ }}ConstraintLayout(可选依赖)SubcomposeLayout 用于先测后绘/延迟子项widthIn/heightIn;比例:aspectRatio;层级:zIndexonGloballyPositioned 获取坐标与尺寸;密度:LocalDensitydrawBehind/drawWithContent 自定义绘制clip(RoundedCornerShape(...))、border/backgroundBox(Modifier
.size(88.dp)
.drawBehind { drawCircle(color = Color(0x2288CCFF)) }
){ /* content */ }LazyColumn {
items(items, key = { it.id }) { item -> ItemRow(item) }
}remember 缓存collectAsLazyPagingItems()animate* 系列stickyHeader;网格:LazyVerticalGrid(GridCells)item {}/items {} + key,避免重组抖动contentType 有助回收与复用itemsIndexed;位置动画:animateItemPlacement()val state = rememberLazyListState() + animateScrollToItemLazyPagingItems.loadState 处理加载/错误/重试MaterialTheme(colorScheme, typography, shapes)dynamicDarkColorScheme()isSystemInDarkTheme() 切换;动态色不可用时回退静态方案snackbarHost、topBar、bottomBar 等插槽MaterialTheme.shapes/typography 在组件内复用ButtonDefaults 自定义颜色与内边距NavHost(navController, startDestination = "home") {
composable("home") { Home() }
composable("detail/{id}") { backStack -> Detail(backStack["id"]) }
}hiltViewModel() 或手动提供rememberSaveable + Saver 保存关键状态val navController = rememberNavController()navDeepLink;嵌套图与返回栈保存navArgument + NavType(整型/布尔/枚举/Parcelable)popUpTo/launchSingleTop/restoreState 组合accompanist-navigation-animation 的 AnimatedNavHost(可选)animate*AsState 与 updateTransition 构建状态动画pointerInput、detectTapGestures;协作嵌套滚动rememberAnimatedVisibility;内容切换:AnimatedContent;淡入淡出:CrossfaderememberInfiniteTransition() 周期性动画spring/tween/keyframes、repeatable、snapdraggable/swipeable;rememberSplineBasedDecay() 惯性val alpha by animateFloatAsState(if (shown) 1f else 0f) Box(Modifier.alpha(alpha))
composeTestRule.onNodeWithText(...).assertIsDisplayed()AndroidView 嵌入 View;ComposeView 嵌入 ComposeBaseline Profiles 优化首帧与滚动Modifier.semantics { } 与 testTag 作为稳定选择器setViewCompositionStrategy 管理生命周期createComposeRule()/createAndroidComposeRule<Activity>()performClick/performTextInput;等待:waitUntil/awaitIdleupdate 同步状态;避免重复创建 ViewcollectAsStateWithLifecycle()(lifecycle-runtime-compose)val uiState by viewModel.state.collectAsStateWithLifecycle()
LaunchedEffect + repeatOnLifecycle 收集stateIn/shareIn 稳定曝光 UI 状态keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search)keyboardActions = KeyboardActions(onSearch = { ... })val focus = remember { FocusRequester() } + modifier.focusRequester(focus)val fm = LocalFocusManager.current(fm.clearFocus() 隐藏键盘)TextField/OutlinedTextField;singleLine/maxLinesplaceholder/label;变换:VisualTransformationfocusProperties 自定义焦点转移;监听 onFocusChangedbringIntoViewRequester 与 IME 顶起配合Image(painterResource(R.drawable.cover), contentDescription = null)AsyncImage(model, contentDescription) 占位/错误图contentScale = ContentScale.Crop/Fit/InsideModifier.clip(CircleShape) + border 头像样式val req = ImageRequest.Builder(context) .data(url).crossfade(true) .placeholder(R.drawable.ph).error(R.drawable.err) .build() AsyncImage(model = req, contentDescription = null)
Modifier.semantics { contentDescription = "..." }role = Role.Button;mergeDescendants = trueModifier.clearAndSetSemantics { };状态:stateDescriptionheading() 标记分组标题;禁用项:disabled()toggleable 与描述准确onNode(hasTestTag()/hasContentDescription()) 搭配@Stable/@Immutable;避免可变公开字段remember/derivedStateOf;在动画/列表中避免每帧分配key;避免捕获不稳定 lambdarememberUpdatedState;差分绘制优先contentType 与稳定尺寸,减少重测量@PreviewLightDark;动态色:@PreviewDynamicColors@PreviewFontScale;多设备参数化预览@Preview(showSystemUi = true);背景:showBackground@Preview(device = "id:pixel_6") 等预设@Preview 覆盖光/暗/字体缩放组合statusBarsPadding()/navigationBarsPadding()/systemBarsPadding()BackHandler(enabled) { /* handle back */ }imePadding()/windowInsetsPadding(WindowInsets.ime)