คู่มือนี้อธิบายวิธีสร้างแถบแอปด้านบนแบบไดนามิกใน 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
จะเป็น "รายการ"
- เมื่อคุณเลือกรายการ ข้อความที่อธิบายจำนวนรายการที่เลือก
จะปรากฏใน
- บล็อก
actions
จะกำหนดการดำเนินการที่คุณแสดงในแถบแอปด้านบน หากhasSelection
เป็นจริง ไอคอนแชร์จะปรากฏหลังข้อความ onClick
Lambda ของ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( 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
อนุญาตให้จัดการทั้งการคลิกและการคลิกแบบยาวสำหรับการเลือกรายการ การคลิกจะดำเนินการ ส่วนการคลิกรายการค้างไว้จะ สลับสถานะการเลือก
ผลลัพธ์
