本指南介绍了如何在 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" ) } } }, modifier = modifier ) }
代码要点
AppBarSelectionActions接受所选项索引的Set。topBarText会根据您是否选择任何项而变化。- 当您选择项时,描述所选项数量的文本
会显示在
TopAppBar中。 - 如果您未选择任何项,则
topBarText为“List of items”。
- 当您选择项时,描述所选项数量的文本
会显示在
actions块定义了您在顶部应用栏中显示的操作。如果hasSelection为 true,则文本后会显示一个共享图标。onClicklambda 的IconButton会处理共享操作,当 您点击该图标时。
结果
将可选择列表集成到动态顶部应用栏中
此示例演示了如何将可选择列表添加到动态顶部应用栏:
@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( modifier = modifier, 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允许对项选择进行点击和长按处理。点击会执行操作,而长按项会切换其选择状态。
结果