如何取消 postDelayed() 的执行 [英] How to cancel the execution of postDelayed()

查看:63
本文介绍了如何取消 postDelayed() 的执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个应用程序,其中可以动态创建某种小部件,并且可以通过拖放进行重新排列.我正在尝试实现两件事:

I'm making an app where some sort of widgets are created on the fly and can be re-arranged with drag and drop. I'm trying to implement 2 things:

  1. 长按启动拖放
  2. 短按(或单击)打开菜单以更改某些设置.

但是我遇到了一个问题,我无法取消处理程序的 postdelayed() 函数中的代码.我正在使用以下代码来实现它.

But i'm having a problem where I can't cancel the code in handler's postdelayed() function. I'm using the following code to make it happen.

      _sliders_item[_sliders_counter].setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(final View v, MotionEvent event) {
                Handler hndlr = new Handler();
                Runnable _run = new Runnable() {
                    @Override
                    public void run() {
                        ClipData data = ClipData.newPlainText("", "");
                        View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
                        v.startDrag(data, shadowBuilder, v, 0);
                        v.setVisibility(View.INVISIBLE);
                        _t1.setText("executed");
                        _t1.show();
                    }
                };
                if (_enable_editor) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        hndlr.postDelayed(_run,1000);
                        //return true;
                    }
                    if (event.getAction() == MotionEvent.ACTION_UP){
                        _t1.setText("menu");
                        _t1.show();
                        hndlr.removeCallbacks(_run);
                        //return true;
                    }
                }
                return _enable_editor;
            }
        });

但问题是,当我长按对象时,它工作正常.我可以开始拖放.但是当我短按它时, ACTION_UP 事件的代码执行但 runnable 中的代码仍然执行.短按对象时如何取消可运行代码?

But the problem is, When I long press the object, it works fine. I can initiate the drag and drop. But when I short press it, The code for ACTION_UP event executes but the code inside the runnable still executes. How can I cancel the runnable code when I short press the object?

推荐答案

您必须保留对 RunnablesHandler 的引用,并使用 Handler#removeCallbacks().

You have to keep references to your Runnables and Handler and use Handler#removeCallbacks().

所以基本上:

Handler h = new Handler();
Runnable r = new Runnable() { /* does something */
h.postDelayed(r, 1000);

// When you want to cancel.
h.removeCallbacks(r);

这篇关于如何取消 postDelayed() 的执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆