我正在使用处理程序在RecyclerView列表项中显示计时器。当我按回承载ActivityRecyclerView被完全破坏时,Handler()仍在后台运行。处理程序是在ViewHolder中创建和启动的。有什么方法可以从ViewHolder本身从处理程序中删除回调?

我的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)
    }

}

最佳答案

据我所知,当RecyclerView与活动分离时,在适配器上没有调用任何方法。

尝试在BaseActivityApplication类中创建计时器对象或对象列表,然后按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();
    }

关于java - 在Recycler Adapter中获取onDestroy() Activity ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58389530/

10-10 02:32