views:

261

answers:

2

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. I am writing this app specifically for a touch screen phones only.

+1  A: 

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.

Toni Menzel
Toni this works fine for phones with keypad. Can you suggest some tips for the similar function in case of touch screen phones
Mithraa
Are you sure this fails on touch screens, have you tried? Checkout MotionEvent class
Pentium10
Well you can hold down a button with a finger.. this at least works visually (button is down as long as i keep the finger on the screen).So i would be surprised if this is not trackable by the (just correctly named) onKey handlers..
Toni Menzel
ok toni i will check it out. I am in my office right now. I will let you know as soon as i have tried it. Thanks a lot dude.
Mithraa
+2  A: 

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.

Steve H
Thanks a lot steve...... :)
Mithraa