我正在尝试使用setontouchlistener。例如,如果我按住一个imagebutton 5秒钟,我想做什么,就会收到警报...这是我的处理方式:

    final ImageButton imageButton1 = (ImageButton) findViewById(R.id.imageButton1);

    imageButton1.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // do something
            return false;
        }
    });


x秒后,如何使用setontouchlistener实现类似的功能?

工作解决方案:

imageButton1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mTouchDownTime = event.getEventTime();
                    Log.v("CustomDebug", "Message: " + mTouchDownTime);

                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    long elapsedTime = event.getEventTime() - mTouchDownTime;
                    Log.v("CustomDebug", "Message: " + elapsedTime);

                }
                return false;
            }
        });

最佳答案

onTouch被调用两次,第一次是使用MotionEvent ACTION_DOWN,第二次是使用MotionEvent ACTION_UP

所以伪代码:

if Event == ACTION_DOWN
  saveTime = time();
elseif Event == ACTION_UP and time()-savetime > 5
  doStuff because the guy hold it for 5sec.

07-26 05:00