首页 > 解决方案 > 如何在更改布局管理器时为 Recycler-View 设置动画

问题描述

在我的应用程序设计中,我需要将回收器视图的布局管理器从线性水平更改为网格布局管理器

我需要使这个过渡顺利。谁能建议我如何使之成为可能。

标签: androidandroid-recyclerviewandroid-animationgridlayoutmanagerlinearlayoutmanager

解决方案


为了动画布局管理器的更改,您需要在 上应用布局动画RecyclerView为此您需要按照以下步骤操作:

1)创建一个项目动画文件来动画项目的出现

item_animation.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_mediumAnimTime">

    <translate
        android:fromYDelta="-30%"
        android:toYDelta="0%"
        android:interpolator="@android:anim/decelerate_interpolator" />

    <alpha android:fromAlpha="0"
        android:toAlpha="1"
        android:interpolator="@android:anim/decelerate_interpolator" />

    <scale
        android:fromXScale="115%"
        android:fromYScale="115%"
        android:toXScale="100%"
        android:toYScale="100%"
        android:pivotX="50%"
        android:pivotY="50%"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

</set>

2) 然后在 anim 文件夹中为布局动画创建一个 XML,并将其应用于项目动画,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
    android:animation="@anim/item_animation"
    android:animationOrder="normal"
    android:delay="15%" />

3)现在,当您更改布局管理器(例如从网格布局到线性布局)时,只需将此动画设置为 RecyclerView 以便为以下项目的出现设置动画RecyclerView

   private void runLayoutAnimation(final RecyclerView recyclerView) {
            final Context context = recyclerView.getContext();
            final LayoutAnimationController controller =
                    AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation);

            recyclerView.setLayoutAnimation(controller);
            recyclerView.getAdapter().notifyDataSetChanged();
            recyclerView.scheduleLayoutAnimation();
}
            // Changing the layout manager followed by applying the animation
            recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
            runLayoutAnimation(recyclerView);

推荐阅读