Compose 实现下拉刷新和上拉加载

5,100 阅读7分钟

该咋整

下拉刷新和上拉加载是很多应用必备的功能,但是我在使用了 Compose 重构应用的时候发现 Compose 没有下拉刷新和上拉加载,这可咋整。。。以前原生提供了 SwipeRefreshLayout ,改一改就直接能用,或者是有那么多的开源库,直接添加下依赖进行使用就可以了,但是现在该咋整。。。

翻了一遍官网给出的一堆 Compose 的样例,在 Jetnews 这个样例中有下拉刷新,不过是自定义的,那么咋整。。。拿过来用啊!传说中的 cv工程师 不就是这样嘛!哈哈哈。

开整

最终效果

开整之前先来放一下 Github 地址吧,别忘了是 main 分支哦:

Github 地址:github.com/zhujiang521…

看看实现的效果吧:

下拉刷新.gif

虽然说不怎么好看,但功能是实现了,😂,凑合看吧,不想看实现过程的可以直接去 Github 中下载代码,里面有全部实现的代码。下面来看看是怎么实现的吧!

下拉刷新

我的思路是既然官方的样例中提供了下拉刷新,那么就先看看他是怎么实现的,再根据下拉刷新来实现下上拉加载吧。

这是官方样例的下载地址:github.com/android/com…

先来看看官方下拉刷新的 Composable 的定义:

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun SwipeToRefreshLayout(
    refreshingState: Boolean,
    onRefresh: () -> Unit,
    refreshIndicator: @Composable () -> Unit,
    content: @Composable () -> Unit
) {}

参数很简单对吧,看见名字就大概知道是啥意思了。咱们一个一个来看:

  • refreshingState:刷新状态,为 true 时表示正在刷新,相反则不是正在刷新
  • onRefresh:下拉刷新时需要执行的操作
  • refreshIndicator:直译过来的意思是刷新指示器,但我理解的就是刷新时的控件,也就是上面转圈的 CircularProgressIndicator ,这个可以自己随便放,也可以加一些小动画等等。
  • content:这就是你想刷新的控件内容,没什么可解释的了。

接下来看一下方法体吧:

val refreshDistance = with(LocalDensity.current) { RefreshDistance.toPx() }
val state = rememberSwipeableState(refreshingState) { newValue ->
    if (newValue && !refreshingState) onRefresh()
    true
}

Box(
    modifier = Modifier
        .nestedScroll(state.PreUpPostDownNestedScrollConnection)
        .swipeable(
            state = state,
            anchors = mapOf(
                -refreshDistance to false,
                refreshDistance to true
            ),
            thresholds = { _, _ -> FractionalThreshold(0.5f) },
            orientation = Orientation.Vertical
        )
) {
    content()
    Box(
        Modifier
            .align(Alignment.TopCenter)
            .offset { IntOffset(0, state.offset.value.roundToInt()) }
    ) {
        if (state.offset.value != -refreshDistance) {
            refreshIndicator()
        }
    }

    LaunchedEffect(refreshingState) { state.animateTo(refreshingState) }
}

方法体的代码大概有二十多行,咱们来慢慢分解来看:

val refreshDistance = with(LocalDensity.current) { RefreshDistance.toPx() }

第一行就是将一个固定 dp 值根据像素密度转为像素值,就不多说了。

val state = rememberSwipeableState(refreshingState) { newValue ->
    if (newValue && !refreshingState) onRefresh()
    true
}

下面的 state 用到了 rememberSwipeableState ,那么 rememberSwipeableState 有什么用呢?它会使用默认的动画创建并记住 Swipeable 的状态,可以看到传入了一个 refreshingStaterefreshingState 是咱们传进来的刷新状态,这是它的初始值,后面的是回调回来的新值,在调用onRefresh() 之前,先进行比较滑动状态。

那么。。。这个 state 是个啥呢?咱们来看看它的源码:

@Composable
@ExperimentalMaterialApi
fun <T : Any> rememberSwipeableState(
    initialValue: T,
    animationSpec: AnimationSpec<Float> = AnimationSpec,
    confirmStateChange: (newValue: T) -> Boolean = { true }
): SwipeableState<T> {
    return rememberSaveable(
        saver = SwipeableState.Saver(
            animationSpec = animationSpec,
            confirmStateChange = confirmStateChange
        )
    ) {
        SwipeableState(
            initialValue = initialValue,
            animationSpec = animationSpec,
            confirmStateChange = confirmStateChange
        )
    }
}

奥,原来是 SwipeableState ,里面还使用了 rememberSaveablerememberSaveable 类似于之前说的remember,但是使用保存的实例状态机制,怎么说呢,比如旋转屏幕的时候不会丢掉值,和之前的 onSaveInstanceState 相似。行了,再来看看 rememberSwipeableState 的参数意思吧:

  • initialValue:状态的初始值。
  • animationSpec:用于将动画设置为新状态的默认动画。
  • confirmStateChange:确认或否决状态的变更,上面 rememberSwipeableState 后面的大括号就是它,在 kotlin 中如果最后一个参数是一个函数对象的话可以不写在括号中。

上面的 SwipeableState 就不展开说了,它包含有关任何正在进行的滑动或动画的必要信息,并提供立即或通过启动动画来更改状态的方法。

回到主题吧,先把 state 放在这,下面会用到的。

Box(
    modifier = Modifier
        .nestedScroll(state.PreUpPostDownNestedScrollConnection)
        .swipeable(
            state = state,
            anchors = mapOf(
                -refreshDistance to false,
                refreshDistance to true
            ),
            thresholds = { _, _ -> FractionalThreshold(0.5f) },
            orientation = Orientation.Vertical
        )
) {
    content()
    Box(
        Modifier
            .align(Alignment.TopCenter)
            .offset { IntOffset(0, state.offset.value.roundToInt()) }
    ) {
        if (state.offset.value != -refreshDistance) {
            refreshIndicator()
        }
    }

    LaunchedEffect(refreshingState) { state.animateTo(refreshingState) }
}

这一块大家应该就熟悉了,最外面一个 Box 包裹着布局,Box 相当于 FLutter 中的 Stack ,相当于安卓中的 FrameLayout ,可以实现叠加的效果,先不看 Boxmodefier ,先看它包裹的内容,里面包裹着咱们传进来的想要进行刷新的控件,然后又放了一个 Box,里面包裹着咱们传进来的刷新指示器,最后执行了 LaunchedEffect ,里面根据刷新状态执行了上面 state 的的动画。

到现在为止基本整个流程走下来了,除了上面 Box 中的 modefier 暂时没说。传进来必要的参数,然后在滑动的时候将刷新指示器展示出来,然后执行刷新的操作,很清晰,但是,是怎么滑动的呢?怎么来控制的呢?这就是上面 Box 中的 modefier 干的事了。

之前一直以为 modefier 就是用来设置一些背景啊、边距值啥的,看了这个之后我发现我想的太简单了,里面的 nestedScroll 竟然还可以修改元素以使其参与嵌套的滚动层次结构,swipeable 是在一组预定义状态之间启用滑动手势。

接下来先来看看 swipeable 吧:

  • state:这里将刚才的 state 传了进去,当检测到滑动时, state 的偏移将使用滑动增量来进行更新
  • anchors:成对的锚点和状态,用于将锚点映射到状态,反之亦然。
  • thresholds:指定状态之间的阈值所在的位置。阈值将用于确定滑动停止时要设置为哪个状态的动画。这表示为lambda,它接受两个状态并以 ThresholdConfig 的形式返回它们之间的阈值。这里要注意的是,状态顺序与滑动方向相对应。
  • orientation:可滑动的方向。

swipeable 说完就只剩 nestedScroll 了,上面所用的 PreUpPostDownNestedScrollConnection 是一个 SwipeableState 的扩展方法,咱们来看看究竟干了些什么事:

@ExperimentalMaterialApi
private val <T> SwipeableState<T>.PreUpPostDownNestedScrollConnection: NestedScrollConnection
    get() = object : NestedScrollConnection {
        override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
            val delta = available.toFloat()
            return if (delta < 0 && source == NestedScrollSource.Drag) {
                performDrag(delta).toOffset()
            } else {
                Offset.Zero
            }
        }

        override fun onPostScroll(
            consumed: Offset,
            available: Offset,
            source: NestedScrollSource
        ): Offset {
            return if (source == NestedScrollSource.Drag) {
                performDrag(available.toFloat()).toOffset()
            } else {
                Offset.Zero
            }
        }

        override suspend fun onPreFling(available: Velocity): Velocity {
            val toFling = Offset(available.x, available.y).toFloat()
            return if (toFling < 0) {
                performFling(velocity = toFling)
                available
            } else {
                Velocity.Zero
            }
        }

        override suspend fun onPostFling(
            consumed: Velocity,
            available: Velocity
        ): Velocity {
            performFling(velocity = Offset(available.x, available.y).toFloat())
            return Velocity.Zero
        }
      
        private fun Float.toOffset(): Offset = Offset(0f, this)
        private fun Offset.toFloat(): Float = this.y
    }

哇!代码好长,这都是什么,不着急,慢慢来看,先看方法,实现了 NestedScrollConnection 接口,来看看 NestedScrollConnection 接口有什么东东:

interface NestedScrollConnection {
    fun onPreScroll(available: Offset, source: NestedScrollSource): Offset = Offset.Zero

    fun onPostScroll(
        consumed: Offset,
        available: Offset,
        source: NestedScrollSource
    ): Offset = Offset.Zero

    suspend fun onPreFling(available: Velocity): Velocity = Velocity.Zero

    suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
        return Velocity.Zero
    }
}

发现这个接口一共有四个方法,那就来分别看看都是干啥的吧:

  • onPreScroll:预滚动事件链,由子控件来调用,以允许父母事先消耗部分拖动事件,参数最后说吧。
  • onPostScroll:滚动完成,当分派(滚动)后代进行消费并通知父控件可以消费的剩下的滚动事件时,就会调用此方法。
  • onPreFling:咱们注意到这是一个有 suspend 关键字的方法,所以只能在协程中进行调用。预发射事件链:当孩子们要发射的时候就会调用此方法,允许父控件拦截并消耗部分初始速度。
  • onPostFling:同样有 suspend 关键字,当完成发射的时候进行调用。

上面说的发射其实就是快速滑动,滚动的话就是慢慢滑,速度不一样。

咱们注意到上面参数其实一直是那几个,来看看吧:

  • Offset:不可变的2D浮点偏移量。
  • NestedScrollSourceNestedScrollConnection 中滚动事件的可能来源
  • Velocity: 以像素每秒为单位的二维速度。

看完 NestedScrollConnection 接口的几个方法是什么意思之后应该会有点恍然大明白地感觉,上面的 performDragperformFling 是强制手势流外部提供的拖动增量,就是减弱你拖动的能量,根据不同情况拦截事件,嗯,对,这基本就是 PreUpPostDownNestedScrollConnection 的意思了。

我在看这块代码的时候也有点懵,看不太明白的话打印下日志看看基本就知道了。

上拉加载

看完上面的如果理解了的话上拉加载就很简单了,改个值的事,先来看看哪些地方需要改,首先需要改一下刷新指示器的位置吧:

Box(
    Modifier
        .align(Alignment.BottomCenter)  // 修改成 bottom
        .offset { IntOffset(0, loadRefreshState.offset.value.roundToInt()) }
) {
    if (loadRefreshState.offset.value != loadDistance) {
         refreshIndicator()
    }
}

还有就是修改扩展方法中的值了:

@ExperimentalMaterialApi
private val <T> SwipeableState<T>.LoadPreUpPostDownNestedScrollConnection: NestedScrollConnection
    get() = object : NestedScrollConnection {
        override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
            val delta = available.toFloat()
            return if (delta > 0 && source == NestedScrollSource.Drag) {
                performDrag(delta).toOffset()
            } else {
                Offset.Zero
            }
        }

        override fun onPostScroll(
            consumed: Offset,
            available: Offset,
            source: NestedScrollSource
        ): Offset {
            return if (source == NestedScrollSource.Drag) {
                performDrag(available.toFloat()).toOffset()
            } else {
                Offset.Zero
            }
        }

        override suspend fun onPreFling(available: Velocity): Velocity {
            val toFling = Offset(available.x, available.y).toFloat()
            return if (toFling > 0) {
                performFling(velocity = toFling)
                available
            } else {
                Velocity.Zero
            }
        }

        override suspend fun onPostFling(
            consumed: Velocity,
            available: Velocity
        ): Velocity {
            performFling(velocity = Offset(available.x, available.y).toFloat())
            return Velocity.Zero
        }
    }

看了代码是不是很简单,只是改了 onPreScrollonPreFling 的返回逻辑,就 OK 了,其它和下拉刷新一摸一样,是不是很简单?哈哈哈

下拉刷新和上拉加载我都分开写了 Composable ,组合起来也写了一个,上面的 gif 图中我就使用的是组合起来的,大家可以按需使用,完整代码在 Github 中都有,别忘了给个 star 啊,😂。

回到顶部

这个功能之前 RecyclerView 实现的时候其实挺麻烦的,还需要去添加监听,Compose 实现起来就比较简单了。LazyColum 可以直接控制滚动的位置,来看看官方的样例吧:

@Composable
fun MessageList(messages: List<Message>) {
    val listState = rememberLazyListState()
    // Remember a CoroutineScope to be able to launch
    val coroutineScope = rememberCoroutineScope()

    LazyColumn(state = listState) {
        // ...
    }

    ScrollToTopButton(
        onClick = {
            coroutineScope.launch {
                // Animate scroll to the first item
                listState.animateScrollToItem(index = 0)
            }
        }
    )
}

是不是很简单?只需要一个 animateScrollToItem 方法,如果不需要动画的话使用 scrollToItem 方法即可。来看看实现的效果吧:

回到顶部.gif

这里其实要说一下,如果不使用 listState 的话,就不会记住上次滚动到的地方,所以如果要实时加载数据进行使用的话还是要使用 rememberLazyListState 的。

整完了

差不多了,今天先整到这里吧,这段时间使用 Compose 真的感觉安卓的编码方式变了,看官方的意思是:如果在老项目中当然可以多个 ActivityFragment 相结合进行使用,但是新项目的话最好使用一个。。。完全颠覆了之前多 Activity 的编程方式,但是历史的车轮一直在往前走,既然性能更好,那为什么不用呢,慢慢尝试吧,我还在慢慢往前走,遇到问题了再写文章继续。

今天先到这里了,有什么问题大家可以在评论区告诉我,别忘了点赞评论关注啊,感激不尽!!! Github 地址:github.com/zhujiang521…