Baserecyclerviewhelper执行动画很简单,只需要调用openLoadAnimation函数并且传入内置的动画名就行了。但是这个动画执行机制要么是重复执行,要么是只执行一次,不满足很多特殊情况。
现在有一个需求是当有人发布了新的信息时,需要在列表的顶端插入新的信息,并且执行一个动画。
- 阅读Baserecyclerviewhelper的源码,我发现每次有数据绑定进来的时候都会执行onViewAttachedToWindow函数,所以我们只要在这个函数里面执行动画就可以了,需要注意的是,这个函数会被多次调用,并且需要执行动画的view有可能还未被渲染,所以我们需要做一下view的非空判断。
override fun onViewAttachedToWindow(holder: BaseViewHolder) {
super.onViewAttachedToWindow(holder)
if (mDatasize > 0) {
startanim(mDatasize)
}
}
fun setDataSize(datasize: Int){
mDatasize = datasize;
}
/**
* add animation when you want to show time
*
* @param holder
*/
public fun startanim(datasize:Int) {
for(position in 0..datasize-1){
var viewByPosition = getViewByPosition(position,R.id.rl_item_container)
if (viewByPosition != null) {
val scaleX = ObjectAnimator.ofFloat(viewByPosition, "scaleX", .5f, 1f)
val scaleY = ObjectAnimator.ofFloat(viewByPosition, "scaleY", .5f, 1f)
var rotation = ObjectAnimator.ofFloat(viewByPosition, "rotation", 0f, 15f, -15f, 0f)
//
var duration = ObjectAnimator.ofFloat(viewByPosition, "alpha", 0f, 1f).setDuration(800)
var animatorSet = AnimatorSet()
animatorSet.playTogether(scaleX,scaleY,rotation,duration)
animatorSet.setDuration(800)
animatorSet.start()
animatorSet.addListener(object : Animator.AnimatorListener{
override fun onAnimationRepeat(p0: Animator?) {
}
override fun onAnimationEnd(p0: Animator?) {
mDatasize = 0
}
override fun onAnimationCancel(p0: Animator?) {
}
override fun onAnimationStart(p0: Animator?) {
}
})
}
}
}