本指南介绍了如何在 Compose 中创建动态顶部应用栏,该应用栏会在从列表中选择项目时更改其选项。您可以根据选择状态修改顶部应用栏的标题和操作。
实现动态顶部应用栏行为
此代码定义了一个可组合函数,用于根据项目选择更改顶部应用栏
@Composable fun AppBarSelectionActions( selectedItems: Set<Int>, modifier: Modifier = Modifier, ) { val hasSelection = selectedItems.isNotEmpty() val topBarText = if (hasSelection) { "Selected ${selectedItems.size} items" } else { "List of items" } TopAppBar( title = { Text(topBarText) }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ), actions = { if (hasSelection) { IconButton(onClick = { /* click action */ }) { Icon( imageVector = Icons.Filled.Share, contentDescription = "Share items" ) } } }, ) }
代码要点
AppBarSelectionActions
接受一个选定项目索引的Set
。topBarText
会根据是否有选定的项目而变化。- 选择项目后,描述已选项目数量的文本会显示在
TopAppBar
中。 - 如果没有选定项目,
topBarText
为“List of items”。
- 选择项目后,描述已选项目数量的文本会显示在
actions
块定义了顶部应用栏中显示的操作。如果hasSelection
为 true,则文本后面会出现一个分享图标。IconButton
的onClick
lambda 在图标被点击时处理分享操作。
结果

将可选列表集成到动态顶部应用栏
此示例演示了如何向动态顶部应用栏添加一个可选列表
@Composable private fun AppBarMultiSelectionExample( modifier: Modifier = Modifier, ) { val listItems by remember { mutableStateOf(listOf(1, 2, 3, 4, 5, 6)) } var selectedItems by rememberSaveable { mutableStateOf(setOf<Int>()) } Scaffold( topBar = { AppBarSelectionActions(selectedItems) } ) { innerPadding -> LazyColumn(contentPadding = innerPadding) { itemsIndexed(listItems) { _, index -> val isItemSelected = selectedItems.contains(index) ListItemSelectable( selected = isItemSelected, Modifier .combinedClickable( interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = { /* click action */ }, onLongClick = { if (isItemSelected) selectedItems -= index else selectedItems += index } ) ) } } } }
代码要点
- 顶部栏会根据选中列表项目的数量进行更新。
selectedItems
包含选定项目索引的集合。AppBarMultiSelectionExample
使用Scaffold
来构建屏幕。topBar = { AppBarSelectionActions(selectedItems) }
将AppBarSelectionActions
可组合项设置为顶部应用栏。AppBarSelectionActions
接收selectedItems
状态。
LazyColumn
在垂直列表中显示项目,仅渲染屏幕上可见的项目。ListItemSelectable
表示一个可选列表项。combinedClickable
允许通过点击和长按来处理项目选择。点击执行一个操作,而长按项目则切换其选择状态。
结果
