开发者

what EVENT LISTENER should i use for my android app

开发者 https://www.devze.com 2023-01-01 09:48 出处:网络
In my app, when one particular image button is clicked and held, i must be able to calculate the time for which the image button was held pressed. Can any one help me by giving some simple guidance or

In my app, when one particular image button is clicked and held, i must be able to calculate the time for which the image button was held pressed. Can any one help me by giving some simple guidance or sample code. i am really stuck up here. Is there any specific event listener for this particular requirement开发者_JAVA技巧. I am writing this app specifically for a touch screen phones only.


What you want to use is this:

OnTouchListener touchListener = new OnTouchListener(){
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        Log.d(LOG_TAG, "Action is: " + action);

        switch (action){
        case MotionEvent.ACTION_DOWN:
            timeAtDown = SystemClock.elapsedRealtime();
            break;

        case MotionEvent.ACTION_UP:
            long durationOfTouch = SystemClock.elapsedRealtime() - timeAtDown;
            Log.d(LOG_TAG, "Touch event lasted " + durationOfTouch + " milliseconds.");
            break;
        }
        return false;
    }

};

button.setOnTouchListener(touchListener);

timeAtDown is a long defined as a class field, since it needs to persist between calls to the touchListener. Using this you don't interfere with the button's normal operation either; you can set a click listener which will function properly. Note: The 'click' operation doesn't happen until the touch event's action goes from DOWN (or MOVE) to UP.


Experiment with the on*** callbacks from http://developer.android.com/reference/android/view/KeyEvent.Callback.html.

For example Button.onKeyDown, save the current time in a variable and Button.onKeyDown calculate the difference from last saved time.

0

精彩评论

暂无评论...
验证码 换一张
取 消