首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >LongClick事件发生得太快。如何增加触发它所需的clicktime时间?

LongClick事件发生得太快。如何增加触发它所需的clicktime时间?
EN

Stack Overflow用户
提问于 2011-10-29 03:59:18
回答 7查看 19K关注 0票数 21

在我正在开发的一个应用程序中,我要求用户必须在某个特定操作发生之前单击并按住组件一段时间。

我目前正在使用OnLongClickListener监听longclick,但我发现用来触发OnLongClick事件的点击长度太短了。

例如,假设LongClick事件在单击400ms后触发,但我希望用户在事件触发之前必须单击并按住1200ms。

有没有办法将LongClick事件配置为需要更长的单击时间?

或者,有没有另一种结构可以让我监听更长的点击?

EN

Stack Overflow用户

发布于 2011-11-09 23:56:24

我在Rohan的帮助下找到了一个解决方案:)

我修改了他的答案以满足我的要求。

当用户按下按钮时,就会启动一个线程。线程在我想要的延迟后休眠,然后当它醒来时,它会执行我需要它做的任何代码。当用户松开时,线程将被终止。这就实现了我想要的,因为如果用户在线程唤醒之前松开,线程就会中断,动作就不会发生。

我喜欢这种方法,因为它可以让我在延迟结束后立即执行我的业务逻辑,这很好,因为我可以给用户一些反馈,让他们知道他们已经推了足够长的时间(例如,手机可能会震动)。

这种方法的缺点是:当您想要的操作正在运行时,用户可能会松开按钮,并在所有操作完成之前终止线程。对于我的情况来说,这不是一个大问题,因为我的业务逻辑做得很少;它只触发一个事件,供其他类处理。如果操作没有完全完成,则用户必须重试是可以接受的。

代码比我希望的要长一点,但是如果这是您的应用程序中的一个常见特性,那么它很容易重用。下面是一个代码示例:

代码语言:javascript
运行
复制
protected class MyLongClickListener implements View.OnTouchListener {
    private Thread longClickSensor;

    public boolean onTouch(View view, MotionEvent event) {
        // If the user is pressing down and there is no thread, make one and start it
        if (event.getAction() == MotionEvent.ACTION_DOWN && longClickSensor == null) {
            longClickSensor = new Thread(new MyDelayedAction());
            longClickSensor.start();
        }
        // If the user has let go and there was a thread, stop it and forget about the thread
        if (event.getAction() == MotionEvent.ACTION_UP && longClickSensor != null) {
            longClickSensor.interrupt();
            longClickSensor = null;
        }
        return false;
    }

    private class MyDelayedAction implements Runnable {
        private final long delayMs = 1200;

        public void run() {
            try {
                Thread.sleep(delayMs); // Sleep for a while
                doBusinessLogic();     // If the thread is still around after the sleep, do the work
            } catch (InterruptedException e) { return; }
        }
        private void doBusinessLogic() {
            // Make sure this logic is as quick as possible, or delegate it to some other class
            // through Broadcasted Intents, because if the user lets go while the work is happenening,
            // the thread will be interrupted.
        }
    }
}
票数 3
EN
查看全部 7 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7934245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档