简体   繁体   English

如何在android中检测按钮的时间按下持续时间?

[英]How can I detect time press duration of button in android?

I want to detect time press duration of button by using setOnTouchListener with onTouch method 我想通过使用setOnTouchListeneronTouch方法来检测按钮的时间按下持续时间

How I can do this ? 我怎么能这样做?

you can do it using onTouchListener 你可以使用onTouchListener来做到这onTouchListener

long FirstTouchTime ;
long duration ; 

public boolean onTouchEvent(MotionEvent event) {

    if (event.getAction() == MotionEvent.ACTION_DOWN) 
        FirstTouchTime = System.currentTimeMillis();    

    else if (event.getAction() == MotionEvent.ACTION_UP) {
        duration = System.currentTimeMillis(); - FirstTouchTime ;
        //duration value in millisecond 
    }
}

Maybe something like this : 也许是这样的:

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
            }
         }
      }    
});

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

相关问题 如何在appium测试中长按android记录按钮(在聊天过程中)一段特定的时间,由java - How to long press on android record button(during chat) for a particular time duration in appium test, by java 每次按下按钮时,如何在Android手机中接收新的扫描结果? - How can I receive new scan results in my android phone every time I press a button? Android编程:每次按下屏幕上的按钮时,如何在屏幕上添加文本视图? - Android Programming: How can I add a text view on the screen each time I press a button on the screen? 如何在Android上检测按钮按下的历史记录 - How to detect button press history on Android 如何检测Android中按下按钮的时间 - how to detect the period for which a button is press in android 如何在android中检测长按音量按钮 - how to detect long press of volume button in android 如何在 Android 9 中检测长按电源按钮 - How detect long press Power Button in Android 9 长按检测按钮,然后按android按钮 - Detect button long press and press android button 如何防止用户同时按下两个按钮? - How can I prevent the users to press two button at the same time? 如果按下按钮,如何更改页面? (Android,ViewPager) - How can I change the page if I press the button? (Android, ViewPager)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM