How to remove a runnable from a handler object added by postDelayed?

后端 未结 4 986
一生所求
一生所求 2020-12-08 00:17

I have an \"open\" animation and am using Handler.postDelayed(Runnable, delay) to trigger a \"close\" animation after a short

4条回答
  •  有刺的猬
    2020-12-08 00:22

    If your using recursion, you can acheive this by passing "this". See code below.

    public void countDown(final int c){
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                aq.id(R.id.timer).text((c-1)+"");
                if(c <= 1){
                    aq.id(R.id.timer).gone();
                    mHandler.removeCallbacks(this);
                }else{
                    countDown(c-1);
                }
            }
        }, 1000);
    }
    

    This example will set the text of a TextView (timer) every second, counting down. Once it gets to 0, it will remove the the TextView from the UI and disable the countdown. This is only useful for someone who is using recursion, but I arrived here searching for that, so I'm posting my results.

提交回复
热议问题