what EVENT LISTENER should i use for my android app
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.
精彩评论