[英]How can I inform the RecyclerView that data has changed from within a Timer inside the Adapter
I have a RecyclerView where you can swipe left items to archive them.我有一个 RecyclerView,您可以在其中向左滑动项目以存档它们。 It would first show the undo layout then after 2 seconds it will be archived (now for a first test I just delete the item).
它会首先显示撤消布局,然后在 2 秒后将其存档(现在对于第一次测试,我只是删除了该项目)。 The problem is that using
notifyItemRemoved(pos)
from a Timer thread crashes the app saying that only the original thread that created the view (UI thread) could touch its views.问题是使用 Timer 线程中的
notifyItemRemoved(pos)
会使应用程序崩溃,说只有创建视图的原始线程(UI 线程)可以触摸其视图。 Is there any trick to go around this? go 有什么技巧吗? I use the timer inside the ViewHolder of my RecyclerView.Adapter extended class.
我在我的 RecyclerView.Adapter 扩展 class 的 ViewHolder 中使用计时器。
Here's the code of the timer:这是计时器的代码:
archiveTimer.schedule(new TimerTask() {
@Override
public void run() {
notesController.remove(position);
notesList.remove(position);
queuedForArchive = false;
}
}, 2000);
On activities you can use runOnUiThread but I can't use that either (function MainActivity.runOnUiThread(Runnable)
is not static so I can't use it outside MainActivity)在活动中,您可以使用 runOnUiThread 但我也不能使用(函数
MainActivity.runOnUiThread(Runnable)
不是 static 所以我不能在 MainActivity 之外使用它)
I found a really tricky way of making timed events happen on UI thread without using a timer.我发现了一种非常棘手的方法,可以在不使用计时器的情况下在 UI 线程上发生定时事件。 I noticed that all animators are actually timed and you can impl onAnimationEnd on any Animator you want, so I made an ObjectAnimator that changes alpha of an invisible view from 1 to 1 (no change) and set its duration to 2000ms that I needed.
我注意到所有动画师实际上都是定时的,你可以在任何你想要的动画师上实现 onAnimationEnd,所以我制作了一个 ObjectAnimator,它将不可见视图的 alpha 从 1 更改为 1(没有变化)并将其持续时间设置为我需要的 2000 毫秒。 I used the same code I wanted to use in the timer inside onAnimationEnd() of that Animator and it worked!!!
我使用了我想在该动画器的 onAnimationEnd() 内的计时器中使用的相同代码,它工作了!!! All code was run on UI thread and changes to other layouts did not create any crashes!
所有代码都在 UI 线程上运行,对其他布局的更改不会造成任何崩溃!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.