首先感谢 启舰 前辈,他的 Android自定义控件三部曲 真的很经典,推荐大家去看,本篇文章也是借鉴他的 自定义控件三部曲之动画篇(十三)——实现ListView Item进入动画 完成的。
目录
一.找到为 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.
*
* <p>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.</p>
*
* @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:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="vertical">
<TextView
android:id="@+id/item_tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_blue_dark"
android:foreground="?selectableItemBackground"
android:gravity="center"
android:text="This is item 0"
android:textColor="@android:color/white"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
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