簡體   English   中英

如何檢測Android中按下按鈕的時間

[英]how to detect the period for which a button is press in android

有什么方法可以檢測按鈕按下了多長時間? 我想記錄一下按下按鈕的時間並采取相應的措施。 因此,如果用戶持續按住按鈕5秒鍾,我想在Android上檢測到5秒鍾。

請告訴我

謝謝普蘭尼

使用以下命令確定觸摸持續時間。您可以在if語句中使用它:event.getEventTime()-event.getDownTime()> 5000它以毫秒為單位計算,這意味着在5秒鍾內您需要將此數字設為5000

請勿使用:android.os.SystemClock.elapsedRealtime()-event.getDownTime()它可能會在模擬器上運行,但無法在設備上運行! 不要問我我怎么知道;)

給按鈕一個View.OnTouchListener 您將實現的onTouch方法將使您能夠訪問MotionEvent 然后,使用getFlags(),您將知道用戶何時開始按下按鈕(ACTION_DOWN)和何時停止(ACTION_UP)。 只需記錄發生這種情況的系統時間即可(或按照另一個答案中的建議,getDownTime()會給出您需要的時間,但僅當您具有ACTION_UP標志時)。

    private long timeElapsed = 0L; //make this a global variable

    //tvTouches could be a TextView or Button or other views
    tvTouches.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    timeElapsed = event.getDownTime();
                    Log.d("setOnTouchListener", "ACTION_DOWN at>>>" + event.getDownTime());
                    break;
                case MotionEvent.ACTION_UP:
                    timeElapsed = event.getEventTime() - timeElapsed;
                    Log.d("setOnTouchListener", "ACTION_UP at>>>" + event.getEventTime());
                    Log.d("setOnTouchListener", "Period of time the view is pressed>>>" + timeElapsed);
                    Toast.makeText(getApplicationContext(), "Period of time the view is pressed in milliseconds>>>" + timeElapsed, Toast.LENGTH_SHORT).show();
                    timeElapsed = 0L;
                    //TODO do something when a certain period of time has passed
                    break;
                default:
                    break;
            }
            return true;
        }
    });

在按鈕上注冊一個OnTouchListener。 然后在偵聽器中使用MotionEvent:

http://developer.android.com/reference/android/view/MotionEvent.html

然后使用Event的getDownTime()方法:

http://developer.android.com/reference/android/view/MotionEvent.html#getDownTime%28%29

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM