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

标签 android android-recyclerview android-animation gridlayoutmanager linearlayoutmanager

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

我需要让这个过渡顺利进行。 谁能建议我如何让它成为可能。

最佳答案

为了动画化布局管理器的变化,您需要在 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);

关于android - 如何在更改布局管理器时为 Recycler-View 设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51344339/

相关文章:

安卓 : Make 2 services communicate

java - 无法在 Android 模拟器上 root

android - 如何将 adb screenrecord 输出重定向到 pc(windows/linux) 存储

android - 无法在 recyclerview 中加载来自 picasso 的图像?

Android:方向更改后自定义动画丢失

android - 在 Android 中应用移动动画后,单击操作在 android 按钮中不起作用

android - Android Studio 上的向后兼容性 (AppCompat)

android - lateinit 属性绑定(bind)尚未初始化

android - 添加页脚 View 后在回收站 View 中仅显示一项

android - 在滑动时创建从一种布局到另一种布局的透明扩展圆圈过渡动画