滚动

滚动修饰符

verticalScrollhorizontalScroll 修饰符提供一种最简单的方法,可让用户在元素内容边界大于最大尺寸约束时滚动元素。利用 verticalScrollhorizontalScroll 修饰符,您无需转换或偏移内容。

@Composable
private fun ScrollBoxes() {
    Column(
        modifier = Modifier
            .background(Color.LightGray)
            .size(100.dp)
            .verticalScroll(rememberScrollState())
    ) {
        repeat(10) {
            Text("Item $it", modifier = Modifier.padding(2.dp))
        }
    }
}

响应滚动手势的简单垂直列表

借助 ScrollState,您可以更改滚动位置或获取其当前状态。如需使用默认参数创建此列表,请使用 rememberScrollState()

@Composable
private fun ScrollBoxesSmooth() {
    // Smoothly scroll 100px on first composition
    val state = rememberScrollState()
    LaunchedEffect(Unit) { state.animateScrollTo(100) }

    Column(
        modifier = Modifier
            .background(Color.LightGray)
            .size(100.dp)
            .padding(horizontal = 8.dp)
            .verticalScroll(state)
    ) {
        repeat(10) {
            Text("Item $it", modifier = Modifier.padding(2.dp))
        }
    }
}

可滚动的修饰符

scrollable 修饰符与滚动修饰符不同,scrollable 会检测滚动手势并捕获增量,但不会自动偏移其内容。而是通过 ScrollableState 委派给用户,而这是此修饰符正常运行所必需的。

构建 ScrollableState 时,您必须提供一个 consumeScrollDelta 函数,该函数将在每个滚动步骤(通过手势输入、平滑滚动或快速滑动)调用,并且增量以像素为单位。此函数必须返回使用的滚动距离量,以确保在存在具有 scrollable 修饰符的嵌套元素时正确传播事件。

以下代码段可检测手势并显示偏移量的数值,但不会偏移任何元素:

@Composable
private fun ScrollableSample() {
    // actual composable state
    var offset by remember { mutableStateOf(0f) }
    Box(
        Modifier
            .size(150.dp)
            .scrollable(
                orientation = Orientation.Vertical,
                // Scrollable state: describes how to consume
                // scrolling delta and update offset
                state = rememberScrollableState { delta ->
                    offset += delta
                    delta
                }
            )
            .background(Color.LightGray),
        contentAlignment = Alignment.Center
    ) {
        Text(offset.toString())
    }
}

一个界面元素,用于检测手指按下操作并显示手指位置的数值

嵌套滚动

嵌套滚动是一种系统,其中包含的多个滚动组件通过响应单个滚动手势并传达其滚动增量(更改)来协同工作。

借助嵌套滚动系统,可滚动和分层关联的组件之间可以相互协调(通常通过共享同一个父项实现)。此系统关联了滚动容器,并允许与之间传播和共享的滚动增量进行交互。

Compose 提供了多种方法来处理可组合项之间的嵌套滚动。嵌套滚动的一个典型示例是另一个列表中的列表,而收起工具栏则更为复杂。

自动嵌套滚动

简单的嵌套滚动无需您执行任何操作。启动滚动操作的手势会自动从子级传播到父级,这样一来,当子级无法进一步滚动时,手势就会由其父元素处理。

Compose 的部分组件和修饰符(verticalScrollhorizontalScrollscrollableLazy API 和 TextField)支持自动嵌套滚动,且开箱即用。这意味着,当用户滚动嵌套组件的内部子级时,之前的修饰符会将滚动增量传播到支持嵌套滚动的父级。

下例展示的是在同样应用了 verticalScroll 修饰符的容器中对元素应用了 verticalScroll 修饰符。

@Composable
private fun AutomaticNestedScroll() {
    val gradient = Brush.verticalGradient(0f to Color.Gray, 1000f to Color.White)
    Box(
        modifier = Modifier
            .background(Color.LightGray)
            .verticalScroll(rememberScrollState())
            .padding(32.dp)
    ) {
        Column {
            repeat(6) {
                Box(
                    modifier = Modifier
                        .height(128.dp)
                        .verticalScroll(rememberScrollState())
                ) {
                    Text(
                        "Scroll here",
                        modifier = Modifier
                            .border(12.dp, Color.DarkGray)
                            .background(brush = gradient)
                            .padding(24.dp)
                            .height(150.dp)
                    )
                }
            }
        }
    }
}

响应内部元素内外的手势的两个嵌套垂直滚动界面元素

使用 nestedScroll 修饰符

如果您需要在多个元素之间创建高级协调滚动,可以使用 nestedScroll 修饰符定义嵌套滚动层次结构,为您提供更大的灵活性。如上一部分所述,某些组件内置了嵌套滚动支持。不过,对于不可自动滚动的可组合项(例如 BoxColumn),此类组件上的滚动增量不会在嵌套滚动系统中传播,并且增量不会到达 NestedScrollConnection 和父组件。如需解决此问题,您可以使用 nestedScroll 向其他组件(包括自定义组件)提供此类支持。

嵌套滚动循环

嵌套滚动循环是指在层次结构树中向上和向下分派的滚动增量流,会经过嵌套滚动系统中的所有组件(或节点),例如通过使用可滚动组件和修饰符或 nestedScroll

嵌套滚动循环的阶段

当可滚动组件检测到触发事件(例如手势)时,在实际滚动操作被触发之前,生成的增量会被发送到嵌套滚动系统并经历三个阶段:预滚动、节点消耗和滚动后。

嵌套滚动周期的阶段

在第一个预滚动阶段,接收触发器事件增量的组件会通过层次结构树将这些事件向上分派到最顶层的父项。然后,增量事件将向下弹出,这意味着增量将从最根节点的父项向下传播到启动嵌套滚动循环的子项。

滚动前阶段 - 向上分派

这样一来,嵌套的滚动父级(使用 nestedScroll 或可滚动修饰符的可组合项)有机会在节点本身使用增量之前对增量执行某些操作。

滚动前阶段 - 向下弹出气泡

在节点使用阶段,节点本身将使用其父级未使用的任何增量。这是滚动移动实际完成且可见的时间。

节点使用阶段

在此阶段,子级可以选择使用全部或部分剩余滚动。剩下的所有内容都将被重新发送回滚动后阶段。

最后,在滚动后阶段,节点本身未使用的任何内容都会再次发送到其祖先实体以供使用。

滚动后阶段 - 向上分派

滚动后阶段的运作方式与滚动前阶段类似,其中任何父级都可以选择是否使用。

滚动后阶段 - 向下弹出

与滚动类似,当拖动手势结束时,用户的意图可能会转换为用于快速滑动(使用动画滚动)可滚动容器的速度。快速滑动也是嵌套滚动周期的一部分,并且拖动事件生成的速度会经历类似的阶段:快速滑动、节点消耗和快速滑动后。请注意,快滑动画仅与轻触手势相关联,不会由其他事件(例如 a11y 或硬件滚动)触发。

参与嵌套滚动循环

参与循环意味着拦截、使用和报告层次结构沿层次结构的增量消耗。Compose 提供了一组工具,以影响嵌套滚动系统的工作原理以及如何直接与嵌套滚动系统交互,例如,当您需要对可滚动组件执行某些操作时,可滚动的组件甚至开始滚动。

如果嵌套滚动周期是一个对节点链执行操作的系统,则 nestedScroll 修饰符可以拦截并插入这些更改,并影响在链中传播的数据(滚动增量)。此修饰符可以放在层次结构中的任何位置,它与树中的嵌套滚动修饰符实例进行通信,以便通过此渠道共享信息。此修饰符的构建块是 NestedScrollConnectionNestedScrollDispatcher

NestedScrollConnection 可用于响应嵌套滚动周期的各个阶段并影响嵌套滚动系统。它包含 4 种回调方法,每种方法分别代表一个使用阶段:滚动前/滚动后和快速滑动后:

val nestedScrollConnection = object : NestedScrollConnection {
    override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
        println("Received onPreScroll callback.")
        return Offset.Zero
    }

    override fun onPostScroll(
        consumed: Offset,
        available: Offset,
        source: NestedScrollSource
    ): Offset {
        println("Received onPostScroll callback.")
        return Offset.Zero
    }
}

每个回调还提供有关传播的增量的信息:该特定阶段的 available 增量和前几个阶段使用的 consumed 增量。如果您在任何时候想停止将增量传播到层次结构中,可以使用嵌套滚动连接来实现此目的:

val disabledNestedScrollConnection = remember {
    object : NestedScrollConnection {
        override fun onPostScroll(
            consumed: Offset,
            available: Offset,
            source: NestedScrollSource
        ): Offset {
            return if (source == NestedScrollSource.SideEffect) {
                available
            } else {
                Offset.Zero
            }
        }
    }
}

所有回调均提供有关 NestedScrollSource 类型的信息。

NestedScrollDispatcher 用于初始化嵌套滚动循环。使用调度程序并调用其方法会触发循环。可滚动容器具有内置调度程序,可将在手势过程中捕获的增量发送到系统中。因此,大多数自定义嵌套滚动的用例涉及使用 NestedScrollConnection(而非调度程序)来响应现有的增量,而不是发送新的增量。如需了解更多用法,请参阅 NestedScrollDispatcherSample

嵌套滚动互操作性

当您尝试在可滚动的可组合项中嵌套可滚动的 View 元素时(反之亦然),可能会遇到问题。当您滚动子项并达到其开始或结束边界,并预期父项接管滚动操作时,会发生最明显的变更。不过,这种预期行为可能不会发生,也可能无法按预期运行。

此问题是由可滚动的可组合项中内置的预期行为而导致。可滚动的可组合项有“默认嵌套滚动”规则,这意味着任何可滚动容器都必须通过 NestedScrollConnection 作为父项参与嵌套滚动链,并通过 NestedScrollDispatcher 作为子项参与嵌套滚动链。然后,当子项位于边界上时,子项将为父项推动嵌套滚动。例如,此规则允许 Compose Pager 和 Compose LazyRow 良好地配合工作。然而,当使用 ViewPager2RecyclerView 完成互操作性滚动时,由于不会实现 NestedScrollingParent3,因此无法做到由子项到父项的连续滚动。

如要在可滚动的 View 元素与可滚动的可组合项之间实现双向嵌套的嵌套滚动互操作 API,您可以在下列场景中使用嵌套滚动互操作 API 来缓解这些问题。

包含子级 ComposeView 的协作式父级 View

协作式父级 View 已实现 NestedScrollingParent3,因此能够从协作式嵌套子级可组合项接收滚动增量。在这种情况下,ComposeView 将充当子项,并且需要(间接)实现 NestedScrollingChild3。合作父级的一个示例是 androidx.coordinatorlayout.widget.CoordinatorLayout

如果您需要在可滚动的 View 父级容器与嵌套的可滚动子级可组合项之间实现嵌套滚动互操作性,可以使用 rememberNestedScrollInteropConnection()

rememberNestedScrollInteropConnection() 会允许并记住 NestedScrollConnection,后者支持在实现 NestedScrollingParent3View 父项和 Compose 子项之间实现嵌套滚动互操作性。此方法应与 nestedScroll 修饰符结合使用。由于嵌套滚动在 Compose 端默认处于启用状态,因此您可以使用此连接在 View 端同时启用嵌套滚动,并在 Views 和可组合项之间添加必要的粘合逻辑。

一个常见的用例是使用 CoordinatorLayoutCollapsingToolbarLayout 和可组合子项,如以下示例所示:

<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:fitsSystemWindows="true">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <!--...-->

        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>

    <androidx.compose.ui.platform.ComposeView
        android:id="@+id/compose_view"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

在您的 activity 或 fragment 中,您需要设置子级可组合项和必需的 NestedScrollConnection

open class MainActivity : ComponentActivity() {
    @OptIn(ExperimentalComposeUiApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<ComposeView>(R.id.compose_view).apply {
            setContent {
                val nestedScrollInterop = rememberNestedScrollInteropConnection()
                // Add the nested scroll connection to your top level @Composable element
                // using the nestedScroll modifier.
                LazyColumn(modifier = Modifier.nestedScroll(nestedScrollInterop)) {
                    items(20) { item ->
                        Box(
                            modifier = Modifier
                                .padding(16.dp)
                                .height(56.dp)
                                .fillMaxWidth()
                                .background(Color.Gray),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(item.toString())
                        }
                    }
                }
            }
        }
    }
}

包含子级 AndroidView 的父级可组合项

此场景涵盖了当您的父级可组合项包含子级 AndroidView 时,对 Compose 端嵌套滚动互操作 API 的实现。AndroidView 会实现 NestedScrollDispatcher,因为它充当 Compose 滚动父项的子项;还会实现 NestedScrollingParent3,因为它充当 View 滚动子项的父项。然后,Compose 父级将能够从嵌套的可滚动子级 View 接收嵌套滚动增量。

以下示例展示了如何在此场景中通过 Compose 收起工具栏来实现嵌套滚动互操作性:

@Composable
private fun NestedScrollInteropComposeParentWithAndroidChildExample() {
    val toolbarHeightPx = with(LocalDensity.current) { ToolbarHeight.roundToPx().toFloat() }
    val toolbarOffsetHeightPx = remember { mutableStateOf(0f) }

    // Sets up the nested scroll connection between the Box composable parent
    // and the child AndroidView containing the RecyclerView
    val nestedScrollConnection = remember {
        object : NestedScrollConnection {
            override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
                // Updates the toolbar offset based on the scroll to enable
                // collapsible behaviour
                val delta = available.y
                val newOffset = toolbarOffsetHeightPx.value + delta
                toolbarOffsetHeightPx.value = newOffset.coerceIn(-toolbarHeightPx, 0f)
                return Offset.Zero
            }
        }
    }

    Box(
        Modifier
            .fillMaxSize()
            .nestedScroll(nestedScrollConnection)
    ) {
        TopAppBar(
            modifier = Modifier
                .height(ToolbarHeight)
                .offset { IntOffset(x = 0, y = toolbarOffsetHeightPx.value.roundToInt()) }
        )

        AndroidView(
            { context ->
                LayoutInflater.from(context)
                    .inflate(R.layout.view_in_compose_nested_scroll_interop, null).apply {
                        with(findViewById<RecyclerView>(R.id.main_list)) {
                            layoutManager = LinearLayoutManager(context, VERTICAL, false)
                            adapter = NestedScrollInteropAdapter()
                        }
                    }.also {
                        // Nested scrolling interop is enabled when
                        // nested scroll is enabled for the root View
                        ViewCompat.setNestedScrollingEnabled(it, true)
                    }
            },
            // ...
        )
    }
}

private class NestedScrollInteropAdapter :
    Adapter<NestedScrollInteropAdapter.NestedScrollInteropViewHolder>() {
    val items = (1..10).map { it.toString() }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): NestedScrollInteropViewHolder {
        return NestedScrollInteropViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.list_item, parent, false)
        )
    }

    override fun onBindViewHolder(holder: NestedScrollInteropViewHolder, position: Int) {
        // ...
    }

    class NestedScrollInteropViewHolder(view: View) : ViewHolder(view) {
        fun bind(item: String) {
            // ...
        }
    }
    // ...
}

此示例展示了如何将该 API 与 scrollable 修饰符结合使用:

@Composable
fun ViewInComposeNestedScrollInteropExample() {
    Box(
        Modifier
            .fillMaxSize()
            .scrollable(rememberScrollableState {
                // View component deltas should be reflected in Compose
                // components that participate in nested scrolling
                it
            }, Orientation.Vertical)
    ) {
        AndroidView(
            { context ->
                LayoutInflater.from(context)
                    .inflate(android.R.layout.list_item, null)
                    .apply {
                        // Nested scrolling interop is enabled when
                        // nested scroll is enabled for the root View
                        ViewCompat.setNestedScrollingEnabled(this, true)
                    }
            }
        )
    }
}

最后,此示例展示了如何将嵌套滚动互操作 API 与 BottomSheetDialogFragment 结合使用,以实现成功的拖动和关闭操作:

class BottomSheetFragment : BottomSheetDialogFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val rootView: View = inflater.inflate(R.layout.fragment_bottom_sheet, container, false)

        rootView.findViewById<ComposeView>(R.id.compose_view).apply {
            setContent {
                val nestedScrollInterop = rememberNestedScrollInteropConnection()
                LazyColumn(
                    Modifier
                        .nestedScroll(nestedScrollInterop)
                        .fillMaxSize()
                ) {
                    item {
                        Text(text = "Bottom sheet title")
                    }
                    items(10) {
                        Text(
                            text = "List item number $it",
                            modifier = Modifier.fillMaxWidth()
                        )
                    }
                }
            }
            return rootView
        }
    }
}

请注意,rememberNestedScrollInteropConnection() 会在附加到它的元素中安装 NestedScrollConnectionNestedScrollConnection 负责将增量从 Compose 级别传输到 View 级别。这使元素能够参与嵌套滚动,但不会自动启用元素滚动。对于不可自动滚动的可组合项(例如 BoxColumn),此类组件上的滚动增量不会在嵌套滚动系统中传播,并且增量不会到达 rememberNestedScrollInteropConnection() 提供的 NestedScrollConnection,因此这些增量不会到达父级 View 组件。如需解决此问题,请确保同时将可滚动修饰符设置为这些类型的嵌套可组合项。如需了解详情,您可以参阅上一部分有关嵌套滚动的部分。

非协作式父级 View,包含子级 ComposeView

非协作式 View 无法在 View 端实现必要的 NestedScrolling 接口。请注意,这意味着这类 Views 不能直接支持嵌套滚动互操作性。非协作式 ViewsRecyclerViewViewPager2