Search code examples
androidtouch-event

Android Screen Touch Action


I am working on an android project where I need to know if user is Touch Down the screen or Touch Up the screen and I frequently need this. How can I do that? I used on Touch Event in switch case for action Up and action down but that works for only one time. I also tried the bellow code but it gives me the the value of var(int variable) for first touch only.

my code:

int var=-1;
@Override
public boolean onTouchEvent(MotionEvent event) {

    int action = event.getAction();

    if(action==MotionEvent.ACTION_DOWN)var=1;
    if(action==MotionEvent.ACTION_UP)var=0;
    if(action==MotionEvent.ACTION_MOVE)var=1;

    return super.onTouchEvent(event); 
}

I need the value of var again and again.


Solution

  • Since onTouchEvent is the last point of touch event traversal, it might not be called if one of the children has consumed touch event already (of if you returned false for MotionEvent.ACTION_DOWN event indicating that you are not interested in this gesture at all).

    For your problem I would rather use dispatchTouchEvent() instead of onTouchEvent() and track touches there.

    For more information I highly recommend getting yourself familiar with talk from Dave Smith about Android Touch System