如何防止双击按钮重复动作? [英] How to prevent repeating actions on double click on the button?

查看:182
本文介绍了如何防止双击按钮重复动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在onClick()中的操作.问题是,如果我按两次按钮,新活动将被打开两次.我尝试使用setEnabled()和setClickable(),但是它不起作用.它仍然显示了一项以上的活动

Here are my actions in onClick(). The problem is that if I press the button twice, the new activity will be opened twice. I tried to use setEnabled() and setClickable(), but it does not work. It still shows more then one activity

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), 
CalendarActivity.class);
            intent.putExtra("day", 16);
            intent.putExtra("month", 12);
            intent.putExtra("year", 1996);
            startActivityForResult(intent, CALENDAR_ACTIVITY_CODE);
        }
    });

推荐答案

这实际上是一个令人惊讶的复杂问题.问题的根源在于,UI事件(例如,单击按钮)导致 messages 被发布"到消息队列的末尾.如果速度足够快,则有可能在处理第一个消息之前将其中许多消息发布到消息队列中.

This is actually a surprisingly complex problem. The root of the issue is that UI events (e.g. a button click) cause messages to be "posted" to the end of a message queue. If you are fast enough, it's possible to get many of these messages posted to the message queue before the first one is ever processed.

这意味着即使禁用onClick()方法中的按钮也无法真正解决问题(因为在处理第一条消息之前,禁用不会发生",但是您可能已经在等待其他三条重复的消息了)在邮件队列中.)

This means that even disabling the button inside your onClick() method won't truly solve the problem (since the disabling won't "happen" until the first message is processed, but you might already have three other duplicate messages waiting in the message queue).

最好的办法是在onClick()内跟踪某种布尔标志并每次检查标志:

The best thing to do is to track some sort of boolean flag and check the flag every time inside onClick():

private boolean firstClick = true;

button.setOnClickListener(v -> {
    if (firstClick) {
        firstClick = false;
        // do your stuff
    }
});

当然,每当您要重新启用按钮点击时,都必须记住将firstClick重置为true.

You have to remember to reset firstClick back to true whenever you want to re-enable button taps, of course.

这篇关于如何防止双击按钮重复动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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