首先,在布局文件中添加 MotionLayout 包装器和 RecyclerView 组件:
然后,在 MotionScene XML 文件中定义 RecyclerView 动画过渡:
注意:在
标签中,使用 dragUp
以显示正确的 RecyclerView 动画方向。
最后,在 RecyclerView 的 Adapter 中启用动画:
class MyAdapter : RecyclerView.Adapter() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindData()
setAnimation(holder.itemView)
}
override fun getItemCount() = 10
private var lastPosition = -1
private fun setAnimation(view: View) {
if (lastPosition < 0) lastPosition = view.layoutPosition
if (lastPosition < view.layoutPosition) {
val animation = AnimationUtils.loadAnimation(view.context, android.R.anim.slide_in_left)
view.startAnimation(animation)
lastPosition = view.layoutPosition
}
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindData() {
// bind data to view
}
}
}
这样就可以显示正确的 RecyclerView 动画方向了。