为 RecyclerView 的列表条目 item 添加动画

首先感谢 启舰 前辈,他的 Android自定义控件三部曲 真的很经典,推荐大家去看,本篇文章也是借鉴他的 自定义控件三部曲之动画篇(十三)——实现ListView Item进入动画 完成的。

目录

一.找到为 item 添加动画的合适位置

二.使用 Animation 创建 item 动画

1.创建 item 的布局 xml 

2.adapter 类

3.从 xml 中加载 item 的动画

4.主界面 MainActivity

5.效果


一.找到为 item 添加动画的合适合适位置

想为 item 添加入场动画,就要在 RecyclerView 的 adapter 中做文章。

我希望列表 item 能够在每次 进入屏幕可见区域的时候都执行动画,而不是只在进入列表界面的时候有动画(像BaseRecyclerViewAdapterHelper那样的item入场动画),那就去 RecyclerView.Adapter 下找一找有没有和 item 可见性相关的方法。那就是 onViewAttachedToWindow(VH holder) 方法。

/**
 * Called when a view created by this adapter has been attached to a window.
 *
 * 

This can be used as a reasonable signal that the view is about to be seen * by the user. If the adapter previously freed any resources in * {@link #onViewDetachedFromWindow(RecyclerView.ViewHolder) onViewDetachedFromWindow} * those resources should be restored here.

* * @param holder Holder of the view being attached */ public void onViewAttachedToWindow(@NonNull VH holder) { }

注释翻译大意:该方法在 adapter 创建的 view 依附到 window 中时调用,这能用作 view 刚好对用户可见的合理信号。

通过 VH holder 可以获取 itemView,进而为 itemView 添加动画。

 

二.使用 Animation 创建 item 动画

1.创建 item 的布局 xml 

item_layout.xml:




    

 

2.adapter 类

package com.leading.recyclerviewitemsanimationtest;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import 

你可能感兴趣的:(android,RecyclerView,RecyclerView,item动画)