使用LayoutAnimationController为RecyclerView添加动画

简介: ### 使用LayoutAnimationController为RecyclerView添加动画 @author:莫川 #### 一、前言 为RecyclerView的Item添加动画有很多中方案,比如通过[设置setItemAnimator来实现](https://github.com/wasabeef/recyclerview-animators)或者是[通过遍历Recycler

使用LayoutAnimationController为RecyclerView添加动画

@author:莫川

一、前言

为RecyclerView的Item添加动画有很多中方案,比如通过设置setItemAnimator来实现或者是通过遍历RecyclerView中的子View,然后分别对子View做动画。今天介绍一种更加简单的方式:通过LayoutAnimationController的方式,对RecyclerView的Item做动画。

二、效果以及源码

先看效果:首先是对LinearLayoutManager的RecyclerView。

  • 1.使用LayoutAnimationController的8种动画的播放效果

img

  • 2.使用GridLayoutAnimationController的8种动画的播放效果

img

Github源码:https://github.com/nuptboyzhb/RecyclerViewAnimation

三、实现方案

(1)LayoutAnimationController

比如实现从依次从左侧进入的动画效果,我们首先需要实现一个Item的动画效果,然后创建一个LayoutAnimationController对象,并设置每一个item播放动画的时间延时和item的播放顺序。

以从左侧进入为例,每个单独的Item的动画如下:

  • 1.Item动画

    ...
    /**
     * 从左侧进入,并带有弹性的动画
     *
     * @return
     */
    public static AnimationSet getAnimationSetFromLeft() {
        AnimationSet animationSet = new AnimationSet(true);
        TranslateAnimation translateX1 = new TranslateAnimation(RELATIVE_TO_SELF, -1.0f, RELATIVE_TO_SELF, 0.1f,
                RELATIVE_TO_SELF, 0, RELATIVE_TO_SELF, 0);
        translateX1.setDuration(300);
        translateX1.setInterpolator(new DecelerateInterpolator());
        translateX1.setStartOffset(0);

        TranslateAnimation translateX2 = new TranslateAnimation(RELATIVE_TO_SELF, 0.1f, RELATIVE_TO_SELF, -0.1f,
                RELATIVE_TO_SELF, 0, RELATIVE_TO_SELF, 0);
        translateX2.setStartOffset(300);
        translateX2.setInterpolator(new DecelerateInterpolator());
        translateX2.setDuration(50);

        TranslateAnimation translateX3 = new TranslateAnimation(RELATIVE_TO_SELF, -0.1f, RELATIVE_TO_SELF, 0f,
                RELATIVE_TO_SELF, 0, RELATIVE_TO_SELF, 0);
        translateX3.setStartOffset(350);
        translateX3.setInterpolator(new DecelerateInterpolator());
        translateX3.setDuration(50);

        animationSet.addAnimation(translateX1);
        animationSet.addAnimation(translateX2);
        animationSet.addAnimation(translateX3);
        animationSet.setDuration(400);

        return animationSet;
    }
    ...

为了让Item看起来有‘弹性’效果,animationSet添加了三个移动动画,分别是从左侧进入(-100%),移动到右侧的10%,然后在从右侧(10%)移动到左侧(-10%),最后再从(-10%)移动到原本的位置(0%)。这样就有了移动后的弹性效果。

  • 2.设置LayoutAnimationController的属性

2.1 设置ViewGroup的子View播放动画之间的offset。

/**
 * Sets the delay, as a fraction of the animation duration, by which the children's animations are offset.
 */
void setDelay(float delay)

2.2 设置ViewGroup的子View播放动画的顺序

/**
 * Sets the order used to compute the delay of each child's animation.
 */
void setOrder(int order)

setOrder可以取值为LayoutAnimationController.ORDER_NORMAL(正常顺序),LayoutAnimationController.ORDER_RANDOM(随机顺序)以及LayoutAnimationController.ORDER_REVERSE(逆序)。这里的demo设置的是正常顺序。

  • 3.播放动画
   /**
     * 播放RecyclerView动画
     *
     * @param animation
     * @param isReverse
     */
    public void playLayoutAnimation(Animation animation, boolean isReverse) {
        LayoutAnimationController controller = new LayoutAnimationController(animation);
        controller.setDelay(0.1f);
        controller.setOrder(isReverse ? LayoutAnimationController.ORDER_REVERSE : LayoutAnimationController.ORDER_NORMAL);

        mRecyclerView.setLayoutAnimation(controller);
        mRecyclerView.getAdapter().notifyDataSetChanged();
        mRecyclerView.scheduleLayoutAnimation();
    }

通过viewGroup.setLayoutAnimation设置layout动画。然后通知ViewGroup重新绘制,调用scheduleLayoutAnimation方法播放动画。

(2)GridLayoutAnimationController

上述方法针对的是线性的RecyclerView,也就是说RecyclerView的LayoutManager设置的是LinearLayoutManager.

    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_list);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(new DemoRecyclerViewAdapter());
    }
    ...

而对于使用GridLayoutManager和StaggeredGridLayoutManager的RecyclerView来说,我们需要使用GridLayoutAnimationController,其他步骤与LayoutAnimationController一致。

    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_grid);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mRecyclerView = (StaggeredGridRecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        mStaggeredGridAdapter = new StaggeredGridAdapter();
        mStaggeredGridAdapter.setDataSet(mockData());
        mRecyclerView.setAdapter(mStaggeredGridAdapter);
    }

    ....

同样的,仍然使用之前的Animation创建GridLayoutAnimationController。

   ...
   /**
     * 播放动画
     *
     * @param animation
     * @param isReverse
     */
    public void playLayoutAnimation(Animation animation, boolean isReverse) {
        GridLayoutAnimationController controller = new GridLayoutAnimationController(animation);
        controller.setColumnDelay(0.2f);
        controller.setRowDelay(0.3f);
        controller.setOrder(isReverse ? LayoutAnimationController.ORDER_REVERSE : LayoutAnimationController.ORDER_NORMAL);

        mRecyclerView.setLayoutAnimation(controller);
        mRecyclerView.getAdapter().notifyDataSetChanged();
        mRecyclerView.scheduleLayoutAnimation();
    }
    ...

GridLayoutAnimationController的delay方法可以分别按照Column和Row维度进行设置。

本以为到此顺利结束。运行后发现,会Crash,log为:

...
E/AndroidRuntime( 7876): java.lang.ClassCastException: android.view.animation.LayoutAnimationController$AnimationParameters cannot be cast to android.view.animation.GridLayoutAnimationController$AnimationParameters
E/AndroidRuntime( 7876):     at android.view.animation.GridLayoutAnimationController.getDelayForView(GridLayoutAnimationController.java:299)
E/AndroidRuntime( 7876):     at android.view.animation.LayoutAnimationController.getAnimationForView(LayoutAnimationController.java:321)
E/AndroidRuntime( 7876):     at android.view.ViewGroup.bindLayoutAnimation(ViewGroup.java:4227)
E/AndroidRuntime( 7876):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3272)
E/AndroidRuntime( 7876):     at android.view.View.draw(View.java:15618)
E/AndroidRuntime( 7876):     at android.support.v7.widget.RecyclerView.draw(RecyclerView.java:3869)
E/AndroidRuntime( 7876):     at android.view.View.updateDisplayListIfDirty(View.java:14495)
E/AndroidRuntime( 7876):     at android.view.View.getDisplayList(View.java:14524)
E/AndroidRuntime( 7876):     at android.view.View.draw(View.java:15315)
E/AndroidRuntime( 7876):     at android.view.ViewGroup.drawChild(ViewGroup.java:3536)
E/AndroidRuntime( 7876):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3329)
E/AndroidRuntime( 7876):     at android.view.View.draw(View.java:15618)
E/AndroidRuntime( 7876):     at android.view.View.updateDisplayListIfDirty(View.java:14495)
E/AndroidRuntime( 7876):     at android.view.View.getDisplayList(View.java:14524)
...

为了解决这个问题,我们需要override RecyclerView的attachLayoutAnimationParameters方法:

package com.github.nuptboyzhb.recyclerviewanimation.grid;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.GridLayoutAnimationController;

/**
 * @version Created by haibozheng on 2016/12/9.
 * @Author Zheng Haibo
 * @Blog github.com/nuptboyzhb
 * @Company Alibaba Group
 * @Description StaggeredGridRecyclerView
 */
public class StaggeredGridRecyclerView extends RecyclerView {

    public StaggeredGridRecyclerView(Context context) {
        super(context);
    }

    public StaggeredGridRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public StaggeredGridRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 支持GridLayoutManager以及StaggeredGridLayoutManager
     *
     * @param child
     * @param params
     * @param index
     * @param count
     */
    @Override
    protected void attachLayoutAnimationParameters(View child, ViewGroup.LayoutParams params,
                                                   int index, int count) {
        LayoutManager layoutManager = this.getLayoutManager();
        if (getAdapter() != null && (layoutManager instanceof GridLayoutManager
                || layoutManager instanceof StaggeredGridLayoutManager)) {

            GridLayoutAnimationController.AnimationParameters animationParams =
                    (GridLayoutAnimationController.AnimationParameters) params.layoutAnimationParameters;

            if (animationParams == null) {
                animationParams = new GridLayoutAnimationController.AnimationParameters();
                params.layoutAnimationParameters = animationParams;
            }

            int columns = 0;
            if (layoutManager instanceof GridLayoutManager) {
                columns = ((GridLayoutManager) layoutManager).getSpanCount();
            } else {
                columns = ((StaggeredGridLayoutManager) layoutManager).getSpanCount();
            }

            animationParams.count = count;
            animationParams.index = index;
            animationParams.columnsCount = columns;
            animationParams.rowsCount = count / columns;

            final int invertedIndex = count - 1 - index;
            animationParams.column = columns - 1 - (invertedIndex % columns);
            animationParams.row = animationParams.rowsCount - 1 - invertedIndex / columns;

        } else {
            super.attachLayoutAnimationParameters(child, params, index, count);
        }
    }
}

更多动画效果,请参见Github源码:https://github.com/nuptboyzhb/RecyclerViewAnimation

四、总结

通过LayoutAnimationController或者GridLayoutAnimationController来实现RecyclerView的动画,非常简单,而且效果很好。该方式不仅可以应用于RecyclerView,而且还适用于ListView、LinearLayout、GridView等ViewGroup。比如,如下是作用在一个LinearLayout的效果。


linearlayout_demo

目录
相关文章
|
人工智能 安全 Docker
打造自己的 Claude Code:LangGraph + MCP 搭建一个极简的 AI 编码助手
本文通过构建一个极简CLI编码代理,探索LangGraph与MCP服务器的底层机制。摒弃商业代理的复杂封装,验证“裸机”LLM代理在无限循环中调用工具的可行性。集成文件操作、网络搜索、GitHub交互等MCP工具,结合Pytest自动化测试与SQLite状态持久化,实现可观察、可调试的智能编码工作流,揭示模型上下文协议的核心价值与实践挑战。
2575 1
打造自己的 Claude Code:LangGraph + MCP 搭建一个极简的 AI 编码助手
|
机器学习/深度学习 编解码 人工智能
计算机视觉五大技术——深度学习在图像处理中的应用
深度学习利用多层神经网络实现人工智能,计算机视觉是其重要应用之一。图像分类通过卷积神经网络(CNN)判断图片类别,如“猫”或“狗”。目标检测不仅识别物体,还确定其位置,R-CNN系列模型逐步优化检测速度与精度。语义分割对图像每个像素分类,FCN开创像素级分类范式,DeepLab等进一步提升细节表现。实例分割结合目标检测与语义分割,Mask R-CNN实现精准实例区分。关键点检测用于人体姿态估计、人脸特征识别等,OpenPose和HRNet等技术推动该领域发展。这些方法在效率与准确性上不断进步,广泛应用于实际场景。
1980 64
计算机视觉五大技术——深度学习在图像处理中的应用
|
人工智能 安全 API
MCP vs 传统集成方案:REST API、GraphQL、gRPC的终极对比
作为一名长期关注AI技术发展的博主摘星,我深刻感受到了当前AI应用集成领域正在经历的巨大变革。随着Anthropic推出的Model Context Protocol(MCP,模型上下文协议)逐渐成熟,我们不得不重新审视传统的系统集成方案。在过去的几年中,REST API凭借其简单易用的特性成为了Web服务的标准选择,GraphQL以其灵活的数据查询能力赢得了前端开发者的青睐,而gRPC则以其高性能的特点在微服务架构中占据了重要地位。然而,当我们将视角转向AI应用场景时,这些传统方案都暴露出了一些局限性:REST API的静态接口设计难以适应AI模型的动态需求,GraphQL的复杂查询机制在处
814 0
MCP vs 传统集成方案:REST API、GraphQL、gRPC的终极对比
|
人工智能 弹性计算 Cloud Native
超强辅助,Bolt.diy 一步搞定创意建站
Bolt.new 是 stackblitz 推出的一款 AI 编辑器,结合人工智能与 WebContainers 技术,支持无需复杂配置的完整开发环境。其开源版本 Bolt.diy 基于阿里云百炼模型服务和函数计算 FC,提供灵活定制、全栈开发支持及多模型适配能力。
|
监控 数据可视化 小程序
项目管理中WBS元素是什么?如何应用?
WBS(工作分解结构)是项目管理中的核心工具,将项目分解为更小、更易于管理的部分。WBS元素是构成WBS的基本单元,代表项目中的特定工作内容或任务。WBS元素最早起源于20世纪50年代的美国,现已广泛应用于建筑、软件开发、市场营销等多个领域。通过WBS元素,项目经理可以明确项目范围、促进资源分配、支持进度规划、便于风险管理、优化沟通协调和控制项目成本。创建WBS元素的过程包括确定项目目标、识别主要工作领域、细分工作领域、定义WBS元素及其关系、验证和更新WBS。尽管WBS元素有许多优点,但也存在需要时间和资源、可能过于复杂及需持续更新的缺点。
项目管理中WBS元素是什么?如何应用?
拯救你的排版噩梦,搞定Deepseek到WPS的完美转换!
使用DeepSeek生成的文案复制到WPS后排版混乱?别担心,本文教你用LibreOffice解决此问题。首先下载并安装LibreOffice,然后将DeepSeek文案粘贴其中,保存为Word格式,最后用WPS打开,排版完美保留。简单四步,轻松搞定!
|
XML 算法 自动驾驶
ROS进阶:使用URDF和Xacro构建差速轮式机器人模型
【11月更文挑战第7天】本篇文章介绍的是ROS高效进阶内容,使用URDF 语言(xml格式)做一个差速轮式机器人模型,并使用URDF的增强版xacro,对机器人模型文件进行二次优化。
1153 6
|
存储 弹性计算 块存储
开发者如何使用块存储EBS
【10月更文挑战第9天】开发者如何使用块存储EBS
1004 4

热门文章

最新文章