Single click and double click of a button in android

前端 未结 9 1329
遇见更好的自我
遇见更好的自我 2020-12-05 22:09

In my application i have a button. After single and double clicking of the button will perform separate operation. How can i do that? Thanks

9条回答
  •  心在旅途
    2020-12-05 22:28

    You may need to create a delay variable which will differenciate between single click and double click.

    See this code,

    private static final long DOUBLE_PRESS_INTERVAL = 250; // in millis
    private long lastPressTime;
    
    private boolean mHasDoubleClicked = false;
    
        @Override
        public boolean onPrepareOptionsMenu(Menu menu) {    
    
            // Get current time in nano seconds.
            long pressTime = System.currentTimeMillis();
    
    
            // If double click...
            if (pressTime - lastPressTime <= DOUBLE_PRESS_INTERVAL) {
                Toast.makeText(getApplicationContext(), "Double Click Event", Toast.LENGTH_SHORT).show();
                mHasDoubleClicked = true;
            }
            else {     // If not double click....
                mHasDoubleClicked = false;
                Handler myHandler = new Handler() {
                     public void handleMessage(Message m) {
                          if (!mHasDoubleClicked) {
                                Toast.makeText(getApplicationContext(), "Single Click Event", Toast.LENGTH_SHORT).show();
                          }
                     }
                };
                Message m = new Message();
                myHandler.sendMessageDelayed(m,DOUBLE_PRESS_INTERVAL);
            }
            // record the last time the menu button was pressed.
            lastPressTime = pressTime;      
            return true;
        }
    

提交回复
热议问题