setontouchlistener x秒

时间:2011-09-12 19:54:38

标签: java android

我正在尝试使用setontouchlistener。如果我按住一个图像按钮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;   
            }
        });

1 个答案:

答案 0 :(得分:2)

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.