我正在将一些AnimatorSet应用于recyclerView的项目,
recyclerView适配器:
class MyAdapter(...) :
androidx.recyclerview.widget.RecyclerView.Adapter<MyAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, p1: Int): ViewHolder {
return ViewHolder(...)
}
override fun onBindViewHolder(p0: ViewHolder, p1: Int) {
p0.bind(...)
}
inner class ViewHolder(itemView: View,...) :
androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
fun bind(...) {
...
animateItemView(itemView)
...
}
}
}
animateItemView函数
fun animateItemView(itemView: View) {
//hide the itemView
itemView.alpha = 0f
//moving the itemView down 400f
ObjectAnimator.ofFloat(itemView, "translationY", 0f, 400f)
.apply { duration = 1L }.start()
//show
//itemView.alpha = 1f
//moving the itemView up 400f
val translateUp = ObjectAnimator.ofFloat(itemView, "translationY", 400f, 0f)
.apply {
duration = 1000L
interpolator = AnticipateOvershootInterpolator(2f)
}
//animating alpha
val fade = ValueAnimator.ofFloat(0f, 1f)
.apply {
addUpdateListener {
itemView.alpha = this.animatedValue as Float
}
duration = 400L
}
//applying
AnimatorSet().apply { playTogether(translateUp, fade) }.start()
}
结果:
当然,当向上滚动itemView
时仍然向上滑动,是否可以应用不同的动画向上/向下滚动,还是有更好的方法?
答案 0 :(得分:1)
我不知道为什么每个人都对将所有内容放入RecyclerView.Adapter
着迷。
您可以将此动画注入RecyclerView.LayoutManager
中,因为它知道添加视图的确切时间和位置:
open class FadeInLinearLayoutManager : LinearLayoutManager {
constructor(context: Context?) : super(context)
constructor(context: Context?, orientation: Int, reverseLayout: Boolean) : super(context, orientation, reverseLayout)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
private val enterInterpolator = AnticipateOvershootInterpolator(2f)
override fun addView(child: View, index: Int) {
super.addView(child, index)
val h = 400f
// if index == 0 item is added on top if -1 it's on the bottom
child.translationY = if(index == 0) -h else h
// begin animation when view is laid out
child.alpha = 0.3f
child.animate().translationY(0f).alpha(1f)
.setInterpolator(enterInterpolator)
.setDuration(1000L)
}
}
然后将其用作布局管理器:
recyclerView.layoutManager = FadeInLinearLayoutManager(context)