在回收器视图中执行由滑动刷新布局时执行布局动画时出现问题



我正在尝试使用XML属性android:layoutAnimation在我的回收器视图中执行自定义动画。

问题是:当我直接在活动的onCreate()中填充适配器时,动画会正常触发。但是,当我尝试从SwipeRefreshLayout.setOnRefreshListener填充我的回收器视图时,动画未正确触发。

我不知道出了什么问题。

依赖

implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.google.android.material:material:1.1.0-alpha04'

XML 文件

活动 XML:

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/postListRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:layoutAnimation="@anim/layout_animation_enter_up"
android:paddingTop="8dp"
android:paddingBottom="8dp" />

layout_animation_enter_up.xml:

<layoutAnimation
xmlns:android="http://schemas.android.com/apk/res/android"
android:animation="@anim/item_animation_enter_up"
android:animationOrder="normal"
android:delay="15%" />

item_animation_enter_up.xml:

<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="600">
<translate
android:fromYDelta="50%p"
android:interpolator="@android:anim/decelerate_interpolator"
android:toYDelta="0" />
<alpha
android:fromAlpha="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:toAlpha="1" />
</set>

简化版我的代码

此代码正确触发layout_animation_enter_up动画:

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_post_list)
val adapter = PostsAdapter()
postListRecyclerView.adapter = adapter
val dummyData = Post(1, "Title", "Body", 1, "Name")
val postList = listOf(dummyData, dummyData, dummyData, dummyData, dummyData, dummyData, dummyData)
adapter.submitList(postList)
}

此代码不会触发layout_animation_enter_up动画:

override fun onCreate(savedInstanceState: Bundle?) {
postListSwipeRefreshLayout.setOnRefreshListener {
val adapter = PostsAdapter()
postListRecyclerView.adapter = adapter
val dummyData = Post(1, "Title", "Body", 1, "Name")
val postList = listOf(dummyData, dummyData, dummyData, dummyData, dummyData, dummyData, dummyData)
adapter.submitList(postList)
}
}

在这两个代码片段(基本相同)中,我认为RecyclerView正在从空状态变为填充状态。如果我在setOnRefreshListener回调或onCreate内填充适配器,UI 角度是否有任何区别?

编辑:上面的代码片段与原始代码库不同,只是为了使解释更容易。我不想知道这个问题的性能。我想知道为什么动画在第二个片段中不起作用,而在第一个片段中工作正常。

基本上,只有在刷新中提交列表时,第一个代码片段应该有效,即:

postListSwipeRefreshLayout.setOnRefreshListener {
adapter.submitList(postList)
}

第二个代码段不应触发动画,因为每次刷新布局时,您都会创建一个新的适配器实例,该实例使适配器无法观察更改。

我不知道为什么每次刷新布局时都要创建一个新实例,但是这会消耗无用实例的内存。

总结:您应该只创建一次实例,并尽可能多地重复使用它,而不是创建新实例。

相关内容

最新更新