RecyclerView 与 LayoutAnimation 实现的进入动画(转)

介绍

原文地址

本教程我们将带大家学习一个为RecyclerView添加初始动画的简单方法。实现这种动画有几种办法,比如:

  • 实现一个自定义的ItemAnimator
  • 在Adapter的onBindViewHolder()方法中添加动画

我将采用第三种办法:LayoutAnimation。它非常简单,而且只需很少的代码。值得注意的是虽然这篇文章是用RecyclerView来做的,但是LayoutAnimation可以用在任何ViewGroup上。


动画效果

本文将讲述:

  • 为每个item定义一个动画
  • 使用item的动画定义LayoutAnimation
  • 在XML或者代码中应用LayoutAnimation

本教程的demo源码点击这里,包含了List和Grid的例子。

让我们开始吧!

首先让我们创建item的动画,这里我们创建的是一个下落的动画:


下落动画

在res/anim/目录下创建一个 item_animation_fall_down.xml 文件并添加如下内容:


 
    
 
    
 
    
 

上面定义的动画元素将会同时运行,这里是对每个动画元素的解释:

  • Translate Y -20% to 0%
    在动画开始前,把view向上移动自身高度的20%,然后让他下降到自己最终的位置。
  • Alpha 0 to 1
    从完全不可见慢慢过渡到完全可见。
  • Scale X/Y 105% to 100%
    放大到105%,然后缩小的实际大小。

定义 LayoutAnimation

定义了item要运行的动画之后,我们来定义把动画应用到每个子view的layout animation。在 res/anim/ 新建一个名为layout_animation_fall_down.xml 的文件,添加如下代码:


  • android:animation="@anim/item_animation_fall_down”
    定义item运行的动画(资源)。
  • android:delay=”15%"
    为每个item动画添加一个延时,基于item动画的duration。0%将导致所有item同步运行,100%则让前一个item的动画运行完了下一个item才开始动画。我们这里使用的是15%,表示item A的动画运行了15%之后才开始运行B的动画。
  • android:animationOrder="normal"
    有三种选择:normal, reverse 和 random。它可以控制布局元素运行动画的顺序。Normal是按照布局的自然顺序( vertical: top to bottom, horizontal: left to right),Reverse跟Normal是相反的,Random则按照随即的顺序。

使用 LayoutAnimation

应用LayoutAnimation可以通过代码实现,也可以通过XML实现。

Java代码:

int resId = R.anim.layout_animation_fall_down;
LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(recyclerView.getContext(), resId);
recyclerview.setLayoutAnimation(animation);

XML:


如果你想在数据变化的时候触发动画:

private void runLayoutAnimation(final RecyclerView recyclerView) {
    final Context context = recyclerView.getContext();
    final LayoutAnimationController controller =
            AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_fall_down);
 
    recyclerView.setLayoutAnimation(controller);
    recyclerView.getAdapter().notifyDataSetChanged();
    recyclerView.scheduleLayoutAnimation();
}

Wrapping up

内容就是这么多了。我觉得这是RecylerView从空到渲染完内容时执行动画的最佳方式。就如我刚才提到的,这种办法适用于所有ViewGroup。
最后附两个动画:

附: Slide from right

item_animation_from_right.xml



 
    
 
    
 

layout_animation_slide_right.xml



这里要注意的是android:fromXDelta="100%p"中的p 不是笔误。当添加了p之后百分比就是基于parent的,所以这里其实代表向右移动parent的整个宽度。

附: Slide from bottom

item_animation_from_bottom.xml



 
    
 
    
 

layout_animation_from_bottom.xml



你可能感兴趣的:(RecyclerView 与 LayoutAnimation 实现的进入动画(转))