如何在更改布局管理器时为Recycler-View设置动画

时间:2018-07-15 00:13:28

标签: android android-recyclerview android-animation gridlayoutmanager linearlayoutmanager

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

我需要使此过渡平滑。 谁能建议我如何实现这一目标。

1 个答案:

答案 0 :(得分:1)

要使布局管理器动画化,您需要在RecyclerView上应用 layout-animation ,为此,您需要执行以下步骤:

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,并将其应用到 item动画,如下所示:

<?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);