首页 > 解决方案 > 如何检测android中按钮的按下时间?

问题描述

setOnTouchListener我想通过使用withonTouch方法检测按钮的按下时间

我怎么能做到这一点?

标签: androidbuttononpress

解决方案


也许是这样的:

long mLastClickTime;

findViewById(R.id.button).setOnTouchListener(new OnTouchListener() {
      @Override
      public void onTouch(View v, MotionEvent event) {
         if (event.getAction() == MotionEvent.ACTION_DOWN) 
            mLastClickTime = SystemClock.elapsedRealtime();

         else if (event.getAction() == MotionEvent.ACTION_UP) {
            long duration = SystemClock.elapsedRealtime() - mLastClickTime;
            // using threshold of 1000 ms
            if (duration > 1000) {
               // do your magic here
            }
         }
      }    
});

推荐阅读