使用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

目录
相关文章
|
API Android开发 容器
33. 【Android教程】悬浮窗:PopupWindow
33. 【Android教程】悬浮窗:PopupWindow
2681 2
|
9月前
|
人工智能 数据安全/隐私保护
阿里AI多款产品亮相第八届中国企业论坛
第八届中国企业论坛在京举行,阿里云受邀参会。通义万相生成开场视频,夸克AI眼镜、阿里云AI Stack等多款AI产品亮相。阿里通义大模型获央国企广泛采用,加速赋能金融、能源、制造等行业智能化升级。(236字)
323 0
|
传感器 存储 Java
Android 3D效果的实现
本文详细讲解了如何在Android中实现3D效果,基于官方Demo并结合实际需求进行调整。通过传感器(Sensor)获取设备旋转数据,利用OpenGL ES绘制3D立方体,实现了动态旋转的视觉效果。文章分为需求分析、效果展示、实现步骤及源码解析,涵盖传感器注册与注销、OpenGL核心方法使用等内容,适合初学者学习参考。文末附完整代码,便于实践操作。
471 0
Android 3D效果的实现
|
人工智能 自然语言处理 程序员
一文彻底搞定从0到1手把手教你本地部署大模型
Ollama 是一个开源工具,旨在简化大型语言模型(LLM)在本地环境的部署与使用。它支持多种预训练模型(如Llama 3、Phi 3等),允许用户根据设备性能选择不同规模的模型,确保高效运行。Ollama 提供了良好的数据隐私保护,所有处理均在本地完成,无需网络连接。安装简便,通过命令行即可轻松管理模型。适用于开发测试、教育研究和个人隐私敏感的内容创作场景。
5435 0
一文彻底搞定从0到1手把手教你本地部署大模型
RecyclerView GridView模式同一行,使其高度平齐,自动适应高度最大item
RecyclerView GridView模式同一行,使其高度平齐,自动适应高度最大item
955 0
|
存储 Java 测试技术
阿里巴巴java开发手册
这篇文章是关于阿里巴巴Java开发手册的整理,内容包括编程规约、异常日志、单元测试、安全规约、MySQL数据库使用以及工程结构等方面的详细规范和建议,旨在帮助开发者编写更加规范、高效和安全的代码。
|
设计模式 Java
常用设计模式介绍~~~ Java实现 【概念+案例+代码】
文章提供了一份常用设计模式的全面介绍,包括创建型模式、结构型模式和行为型模式。每种设计模式都有详细的概念讲解、案例说明、代码实例以及运行截图。作者通过这些模式的介绍,旨在帮助读者更好地理解源码、编写更优雅的代码,并进行系统重构。同时,文章还提供了GitHub上的源码地址,方便读者直接访问和学习。
常用设计模式介绍~~~ Java实现 【概念+案例+代码】
|
设计模式 前端开发 JavaScript
深入探索研究MVVM架构设计
【10月更文挑战第7天】
901 0
|
XML Java API
23. 【Android教程】轮播滚动视图:ViewFlipper
23. 【Android教程】轮播滚动视图:ViewFlipper
971 2
|
Java 开发工具 Android开发
Android经典面试题之开发中常见的内存泄漏,以及如何避免和防范
本文介绍Android开发中内存泄漏的概念及其危害,并列举了四种常见泄漏原因:静态变量持有Context、非静态内部类、资源未释放及监听器未注销。提供了具体代码示例和防范措施,如使用ApplicationContext、弱引用、适时释放资源及利用工具检测泄漏。通过遵循这些建议,开发者可以有效提高应用稳定性和性能。
380 0