[英]Get activity onDestroy() in Recycler Adapter
I am using a Handler to display a timer in RecyclerView
list item.我正在使用处理程序在
RecyclerView
列表项中显示计时器。 When I press back the Activity
that hosts the RecyclerView
is completely destroyed, the Handler()
still running in the background.当我按下承载
RecyclerView
的Activity
时,它被完全破坏, Handler()
仍在后台运行。 The handler is created and initiated in ViewHolder
.处理程序在
ViewHolder
中创建和启动。 Is there any way to remove the callbacks from handler from ViewHolder
itself?有没有办法从
ViewHolder
本身的处理程序中删除回调?
My ViewHolder sample code我的 ViewHolder 示例代码
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), CustomRunnable.CustomRunnableListener{
private val handler = Handler()
lateinit var customRunnable: CustomRunnable //custom runnable for my timer logic
fun bind(position: Int, listModelClass: ModelClass?){
if(someCondition){
customRunnable = CustomRunnable(handler, this, textView, listModelClass)
handler.postDelayed(customRunnable, 1000)
}
}
override fun onTimerFinish(listModelClass: ModelClass) {
// I get this call back when the timer finishes
handler.removeCallbacks(customRunnable)
}
}
As per my knowledge, there is no method on adapter that is called when RecyclerView
is detached from activity.据我所知,当
RecyclerView
与活动分离时,适配器上没有调用任何方法。
Try creating a timer object or a list of objects in your BaseActivity
or Application
Class and after pressing onBack run a method that will stop that timer or timers.尝试在您的
BaseActivity
或Application
Class 中创建一个计时器 object 或对象列表,然后在按下 onBack 后运行一个将停止该计时器或计时器的方法。
//Declare timer
CountDownTimer cTimer = null;
//start timer function
void startTimer() {
cTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
}
};
cTimer.start();
}
//cancel timer
void cancelTimer() {
if(cTimer!=null)
cTimer.cancel();
}
You can do it onDestory() of activity你可以在活动的onDestory()上做
handler.removeCallbacksAndMessages(null);
Remove any pending posts of callbacks and sent messages whose obj is token.
删除所有待处理的回调和发送的消息,其 obj 是令牌。 If token is null, all callbacks and messages will be removed.
如果 token 是 null,所有的回调和消息都会被移除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.