Jetpack compose 實現多個tab頁面, 每個Tab對應一個列表時, 切換時列表會自動滾動到頂部, 解決的辦法很簡單, 執行要設置它的state就可以了,代碼如下:
@Preview(showBackground = false, backgroundColor = 0xffffff)
@Composable
fun DefaultPreview() {
// 記住tab頁狀態
val state = remember { mutableStateOf(0) }
val titles = listOf("Tab1", "Tab2", "Tab3")
val listData = (0..119).toList()
Scaffold(
content = {
Column(modifier = Modifier.fillMaxSize()) {
// 記住列表狀態, 只需將這個設置給 LazyColumn 的 state 即可
val listState0 = rememberLazyListState()
val listState1 = rememberLazyListState()
val listState2 = rememberLazyListState()
UserInfo()
// 滾動table
TabRow(selectedTabIndex = state.value, tabs = {
titles.forEachIndexed { index, s ->
Tab(selected = index == state.value,
onClick = { state.value = index },
text = { Text(text = s) })
}
})
Box(modifier = Modifier.fillMaxWidth()) {
when (state.value) {
0 -> {
LazyColumn(
modifier = Modifier.fillMaxWidth(),
state = listState0,
content = {
items(listData) {
Box(modifier = Modifier.height(100.dp)) {
Text(text = "Item$it")
}
}
})
}
1 -> {
LazyColumn(
modifier = Modifier.fillMaxWidth(),
state = listState1,
content = {
items(listData) {
Box(modifier = Modifier.height(100.dp)) {
Text(text = "Item$it")
}
}
})
}
else -> {
LazyColumn(
modifier = Modifier.fillMaxWidth(),
state = listState2,
content = {
items(listData) {
Box(modifier = Modifier.height(100.dp)) {
Text(text = "Item$it")
}
}
})
}
}
}
}
}
)
}