我有一个要求,需要折叠 TopAppbar 和 Search 视图,并且选项卡布局应该固定在那里。我尝试了不同的方法,但 Searchview 没有折叠,而是固定在 MediumTopApp 栏下方。
[在此处输入图片描述]( https://isstatic.askoverflow.dev/rUq5nDLk.png )
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun MyCollapsingLayout() {
// Define state for tabs
val tabs = listOf("Tab 1", "Tab 2", "Tab 3")
var selectedTabIndex by remember { mutableIntStateOf(0) }
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
// LazyColumn state to detect scrolling
val listState = rememberLazyListState()
Scaffold(
topBar = {
// Wrapping both the MediumTopAppBar and the SearchBar in a single Column
Column(
modifier = Modifier
.nestedScroll(scrollBehavior.nestedScrollConnection) // Attach scroll behavior
.fillMaxWidth()
.zIndex(1f)
) {
// MediumTopAppBar with collapsing behavior
MediumTopAppBar(
title = { Text("Medium AppBar") },
scrollBehavior = scrollBehavior
)
// Search bar is part of the collapsible area
SearchBar()
}
},
content = { padding ->
LazyColumn(
state = listState, // Attach LazyColumn to listen for scrolling
modifier = Modifier
.fillMaxSize()
.padding(padding)
) {
// Sticky header for TabRow, it will stay at the top when scrolled
stickyHeader {
TabRow(
selectedTabIndex = selectedTabIndex,
modifier = Modifier
.fillMaxWidth()
.zIndex(1f) // Ensures the tab stays above scrolling content
) {
tabs.forEachIndexed { index, tab ->
Tab(
selected = selectedTabIndex == index,
onClick = { selectedTabIndex = index },
text = { Text(tab) }
)
}
}
}
// The rest of the scrollable content
items(50) { index ->
ListItem(text = "Item $index")
}
}
}
)
}
@Composable
fun SearchBar() {
// Search Bar composable that will scroll away with the MediumTopAppBar
TextField(
value = "",
onValueChange = {},
placeholder = { Text("Search...") },
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
)
}
@Composable
fun ListItem(text: String) {
Text(
text = text,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
}
我需要折叠 TopAppBar 和 SearchView
现在 TopAppBr 已折叠,但 searchview 固定在那里
公开
scrollBehaviour
一个状态变量scrollBehavior.state.collapsedFraction
。它表示折叠到的百分比TopAppBar
。您可以尝试使用它来为高度设置动画TextField
。首先,允许传入
Modifier
Composable 中SearchBar
:然后,按如下方式调用它:
还请注意,我需要应用
nestedScroll
修改器才能Scaffold
使其工作。输出:
笔记:
根据Material Design 指南,高度
TextField
等于56.dp
高度加上顶部和底部的填充。8.dp