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

本文介绍了如何在 RecyclerView 的 adapter 中利用 onViewAttachedToWindow 方法,根据列表滚动方向为 item 添加不同入场动画。通过监听 RecyclerView 滚动,结合 Animation 和 xml 动画资源,实现了在向上或向下滚动时为列表项添加动画的效果。
摘要由CSDN通过智能技术生成

首先感谢 启舰 前辈,他的 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.
 *
 * <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 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值