Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect tap on the screen?

More specific where do I attach OnGestureListener so that
I can detect onSingleTapUp everywhere on the screen,
even if an ImageView take up half the screen.

Now I have the Listener on the Activity that has an ImageView.
But the Listener only fire when I click outside the ImageView.

I read and try to understand this but cannot get it right.

this code is in the Activity.

 public boolean onSingleTapUp(MotionEvent e) {
    //addtext.setText("-" + "SINGLE TAP UP" + "-");
    //Log.d(TAG, "- + SINGLE TAP UP + - ***********************************************************************");  
    int btnsize = buttonSave.getHeight();
    int viewWidth = display.getWidth();
    int viewHeight = display.getHeight();

    // RIGHT SIDE SCREEN
    if(e.getX()> (viewWidth*0.7)){
        Log.d(TAG, "RIGHT SIDE");
        if(e.getY()> viewHeight*0.7){         
            Log.d(TAG, "right down on screen");
        }else if(e.getY()> (viewHeight*0.45)){ 
            Log.d(TAG, "right middle on screen   ");
        }
    }
    // LEFT SIDE SCREEN
    if(e.getX()< (viewWidth*0.3)){
        Log.d(TAG, "LEFT SIDE");
        if(e.getY()> viewHeight*0.7){ 
            Log.d(TAG, "Left middle on screen  ");
        }else if(e.getY()> (viewHeight*0.45)){
            Log.d(TAG, "Left down on screen ");
        }
    }
    return true;
}
like image 801
Erik Avatar asked Jun 01 '11 18:06

Erik


People also ask

How to Detect touch on Screen Android?

Detecting Common GesturesImplement an OnGestureListener , attach it to a GestureDetector and use it inside the View's OnTouchListener by passing it each touch event the View receives. If the GestureDetector detects any of the gestures is supports, it will trigger its appropriate callback.


2 Answers

Detect Screen Tap

I'm answering this for those who just need a simple way to detect a tap on the screen:

  1. Add an android:onClick value to your base/root layout (LinearLayout, RelativeLayout, etc.). You can call it anything you want, I'm naming it screenTapped as an example:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools" 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:onClick="screenTapped">
    
  2. Add this method to your Activity using the same name you specified for onClick:

    public void screenTapped(View view) {
        // Your code here
    }
    

Now, tapping on the screen will call the method above.

like image 152
Sheharyar Avatar answered Sep 21 '22 21:09

Sheharyar


I'm answering my own question. Thanks to the above @Jason. I have registered onTouchEvent to all views.
It works great.

like image 44
Erik Avatar answered Sep 21 '22 21:09

Erik