您可以顯示按鈕,讓使用者快速捲動至清單中的特定位置,節省時間並提高使用者參與度。
版本相容性
這個實作方式需要將專案 minSDK 設為 API 級別 21 以上。
依附元件
建立按鈕以啟用貼齊捲動功能
請使用下列程式碼,在含有 10 個項目的垂直延遲清單中,建立用於平滑貼齊捲動的按鈕:
@Composable fun MessageList(modifier: Modifier = Modifier) { val listState = rememberLazyListState() val coroutineScope = rememberCoroutineScope() LazyColumn(state = listState, modifier = Modifier.height(120.dp)) { items(10) { index -> Text( modifier = Modifier.height(40.dp), text = "Item $index" ) } } Button(onClick = { coroutineScope.launch { listState.animateScrollToItem(index = 0) } }) { Text(text = "Go top") } }
程式碼的重點
- 使用
listState
物件,記住LazyColumn
的捲動狀態,以便捲動至所選位置。 - 啟動協同程式來呼叫
listState.animateScrollToItem
,在動畫捲動動作時捲動至已編入索引的項目。
結果
![含有啟用按鈕的垂直捲動清單](https://developer.android.com/static/develop/ui/compose/quick-guides/content/snap-scroll.gif?hl=zh-tw)
包含此指南的集合
本指南是精選的快速指南系列之一,涵蓋更廣泛的 Android 開發目標:
![](https://developer.android.com/static/images/quick-guides/collection-illustration.png?hl=zh-tw)
顯示清單或格狀
清單和格線可讓應用程式以視覺上賞心悅目且使用者易於取用的形式顯示集合。
![](https://developer.android.com/static/images/quick-guides/collection-illustration.png?hl=zh-tw)
顯示互動式元件
瞭解可組合函式如何讓您輕鬆根據 Material Design 設計系統,建立美觀的 UI 元件。
![](https://developer.android.com/static/images/quick-guides/collection-illustration.png?hl=zh-tw)
Compose 基本概念 (影片集合)
本系列影片將介紹各種 Compose API,快速向您展示可用的 API 和使用方式。
有問題或意見回饋嗎?
請前往常見問題頁面,瞭解快速指南或與我們聯絡,分享您的想法。