RecyclerView子项Attach动画(非 Item-Animation)
好久没写博客了,太懒了哈哈哈
上效果
今天来一个RecyclerView
子项Attach
动画,比如我在上滑下滑的时候,我希望进入到屏幕的item
做一些动效,比如位移差,缩放等。先看下效果吧:
实现
实现原理呢也是非常非常的简单,直接在RecyclerView.Adapter
中重写onViewAttachedToWindow(ViewHolder)
即可,这个方法可以拿到即将进入屏幕的ViewHolder
:
/**
* 1.需要做一些判断,比如首次加载,不需要执行attach动画,不然会导致第一个item的margin不对
* 2.发现的bug: 如果RecyclerView中的每个Vh高度不一样,比如一屏中有俩个过大的高度,此时向上滑动, 触发
* 上面的item attach,如果attach的item高度过高,会导致RecyclerView可见item数目突变(在动画过程 中),
* 这时候会出现一个Item 闪现。
*
* @param holder Vh
*/
override fun onViewAttachedToWindow(holder: Vh) {
super.onViewAttachedToWindow(holder)
if (isScrollUp) {
ValueAnimator.ofFloat(250f, 0f).apply {
duration = 500L
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener {
holder.itemView.apply {
translationY = it.animatedValue as Float
}
}
start()
}
} else {
ValueAnimator.ofFloat(0f, 250f).apply {
duration = 500L
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener {
holder.itemView.apply {
translationY = it.animatedValue as Float
alpha = (it.animatedValue as Float)
scaleX = (it.animatedValue as Float)
scaleY = (it.animatedValue as Float)
rotation = (it.animatedValue as Float) * 90f
}
}
start()
}
}
}