Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect touch event on a view when dragged over from other view

Tags:

How do I detect the touch event if the user touches on view A and drags to bottom over the view B. I want to detect the touch event in View B.

I added touch listener in view B but doesn't receive events if the user initially touched A and dragged over the B.

enter image description here

like image 215
dcanh121 Avatar asked Oct 19 '12 18:10

dcanh121


1 Answers

You can use the code bellow to achive your request:

Method to test view bounds (used in code beloow)

    Rect outRect = new Rect();     int[] location = new int[2];      private boolean isViewInBounds(View view, int x, int y){         view.getDrawingRect(outRect);         view.getLocationOnScreen(location);         outRect.offset(location[0], location[1]);         return outRect.contains(x, y);     } 

Testing with two TextView

    final TextView viewA = (TextView)  findViewById(R.id.textView);     final TextView viewB = (TextView)  findViewById(R.id.textView2); 

Setup viewA

The empty OnClickListener is required to keep OnTouchListener active until ACTION_UP

    viewA.setOnClickListener(new OnClickListener() {         @Override         public void onClick(View v) {}     });      viewA.setOnTouchListener(new OnTouchListener() {         @Override         public boolean onTouch(View v, MotionEvent event) {             int x = (int)event.getRawX();             int y = (int)event.getRawY();             if(event.getAction() == MotionEvent.ACTION_UP){                 if(isViewInBounds(viewB, x, y))                     viewB.dispatchTouchEvent(event);                 else if(isViewInBounds(viewA, x, y)){                     Log.d(TAG, "onTouch ViewA");                     //Here goes code to execute on onTouch ViewA                 }             }             // Further touch is not handled             return false;         }     }); 

Setup viewB

This is only required if you also want to press on viewB and drag to viewA

    viewB.setOnClickListener(new OnClickListener() {         @Override         public void onClick(View v) {}     });      viewB.setOnTouchListener(new OnTouchListener() {         @Override         public boolean onTouch(View v, MotionEvent event) {             int x = (int)event.getRawX();             int y = (int)event.getRawY();             if(event.getAction() == MotionEvent.ACTION_UP){                 if(isViewInBounds(viewA, x, y))                     viewA.dispatchTouchEvent(event);                 else if(isViewInBounds(viewB, x, y)){                     Log.d(TAG, "onTouch ViewB");                     //Here goes code to execute on onTouch ViewB                 }             }             // Further touch is not handled             return false;         }     }); 

Regards.

like image 168
Luis Avatar answered Oct 22 '22 11:10

Luis