繁体   English   中英

Android如何为UI事件编写简单的计时器?

[英]Android How do I write a simple timer for UI events?

我的应用程序需要检查用户是否双击。 但是我不能使用Android OnDoubleClickListener或类似的东西。 只是实现它:

我的问题与“常规”双击不同。

我想要的是:如果用户双击,请运行Y活动。 如果用户仅单击1次单击,请等待500毫秒,然后运行X活动。 如果用户单击2缓慢单击,请运行X活动

这是我的代码:

        long now = System.currentTimeMillis();
        thisTime = now;

        if (thisTime - lastTouchTime < WAIT_TIME) {
            // Double tap

            this.getContext()
                    .getApplicationContext()
                    .startActivity(
                            (new Intent(getContext(),
                                    ChangePlaceActivity.class))
                                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));

            // If is double tap, reset to start state.
            lastTouchTime = -1;
            return true;
        } else {
            // Too slow or first click
            // If not double tap, save last state for next check

            lastTouchTime = thisTime;

            Log.d("Worker thread", "Declare" + System.currentTimeMillis());
            Thread t = new Thread() {
                public void run()
                {
                    try {
                        sleep(WAIT_TIME);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            };
            t.start();
            try {
                t.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.d("Worker thread", "" + System.currentTimeMillis());

            // start MainAct
            Log.d("Single Click", "Yes");
            this.getContext()
                    .getApplicationContext()
                    .startActivity(
                            (new Intent(getContext(),

                            MainActivity.class))
                                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        }

如果使用这样的代码,我将无法双击。 如果删除thread.run()thread.join()。 它将在ChangePlacecActivity之前启动MainActivity。

有什么解决办法吗? 先感谢您!

对不起,我的英语不好。

您可以为此使用处理程序。 就像是:

(类级别的声明)

Handler handler = new Handler();
Runnable singleClickTask = new Runnable() {
  public void run() {
    //run X activity
    firstClick = true;
  }
};
boolean firstClick = true;

(然后在onClick中)

if (firstClick) {
  handler.postDelayed(singleClickTask, 500);
  firstClick=false;
} else {
  handler.removeCallbacks(singleClickTask);
  firstClick=true;
  //run Y activity
}

在盲目的使用它之前,请自己调试它,但是我认为这是正确的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM