本指南說明如何在 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會是「項目清單」。
- 選取項目時,
actions區塊定義了要在頂端應用程式列顯示的動作。如果hasSelection為 true,文字後方會顯示共用圖示。- 當您點選圖示時,
IconButton的onClicklambda 會處理分享動作。
結果

將可選取清單整合至動態頂端應用程式列
以下範例說明如何將可選取的清單新增至動態頂端應用程式列:
@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允許點擊和長按處理項目選取。點按會執行動作,長按項目則會切換選取狀態。
結果
