搜索栏 (Search)
M3 提供了全屏搜索栏 (SearchBar) 和停靠式搜索栏 (DockedSearchBar)。
1. 全屏搜索栏 (SearchBar)
通常用于主页,点击后展开显示搜索历史或建议。
kotlin
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchBarSample() {
var text by remember { mutableStateOf("") }
var active by remember { mutableStateOf(false) } // 是否展开搜索页
val searchHistory = remember { mutableStateListOf("Android", "Compose", "Kotlin") }
SearchBar(
query = text,
onQueryChange = { text = it },
onSearch = {
active = false
// 执行搜索逻辑
},
active = active,
onActiveChange = { active = it },
placeholder = { Text("搜索...") },
leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
trailingIcon = {
if (active) {
Icon(
modifier = Modifier.clickable {
if (text.isNotEmpty()) text = "" else active = false
},
imageVector = Icons.Default.Close,
contentDescription = "Close"
)
}
}
) {
// 搜索建议区域 (Scaffold 内容)
searchHistory.forEach { history ->
Row(modifier = Modifier.padding(14.dp)) {
Icon(Icons.Default.History, contentDescription = null)
Spacer(Modifier.width(10.dp))
Text(text = history)
}
}
}
}2. 停靠式搜索栏 (DockedSearchBar)
适用于大屏设备,搜索栏不会扩展到全屏,而是像下拉菜单一样悬浮显示结果。用法与 SearchBar 几乎一致,但视觉表现不同。
kotlin
DockedSearchBar(
query = text,
onQueryChange = { text = it },
onSearch = { active = false },
active = active,
onActiveChange = { active = it },
placeholder = { Text("搜索...") },
leadingIcon = { Icon(Icons.Default.Search, null) },
) {
// 搜索建议列表
LazyColumn {
items(searchHistory) { ... }
}
}