根据您所写的内容,您基本上想要一个水平回收器视图,当滚动时该视图具有淡入淡出的动画到标题。
我遇到了同样的问题,我解决了以下问题。我在开发过程中使用了 kotlin。
首先你需要在你的回收器视图中添加一个滚动监听器,我已经为滚动做了一个扩展功能
inline fun RecyclerView.scroll(
crossinline onScrolled: (RecyclerView, Int, Int) -> Unit = { it, dx, dy -> },
crossinline onScrolledChanged: (RecyclerView, Int) -> Unit = { it, newState -> }
) {
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
onScrolled(recyclerView, dx, dy)
}
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
onScrolledChanged(recyclerView, newState)
}
})
}
现在创建一个分隔项装饰器,用于向第一项添加填充
class DividerDecorator(val paddingStart: Float) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val position = parent.getChildAdapterPosition(view)
if (position == 0 || position == 1) {
outRect.left = paddingStart.toInt()
}
val lp = view.layoutParams as StaggeredGridLayoutManager.LayoutParams
val spanIndex = lp.spanIndex
if (position >= 0) {
if(spanIndex==0) {
outRect.top = 13.px
outRect.bottom = 5.px
}else{
outRect.top = 5.px
outRect.bottom = 13.px
}
}
}
}
现在在您的 XML 位置添加您想要作为背景的图像并将回收器视图放在该图像的顶部。
完成后,您只需将滚动扩展添加到您的回收站视图
private var overallScroll = 0;
recycler.scroll(onScrolled = { _, dx, _ ->
overallScroll += dx
backgroundView.animate()
.alpha(overallScroll.remap(padding))
.setInterpolator(LinearInterpolator())
.setDuration(0)
.start()
})
我已经使用 remap 函数来计算对应于滚动位移的正确 alpha。
fun Int.remap(offset:Float):Float{
return 1-(this/offset)
}
是的,别忘了将回收站视图设为水平。