1

I'm kinda trying to clone the ripple effect found in Google's material design. Now, I've noticed that the ripple always starts from the position that was touched. For this, I've created a drawable which will be initially invisible and but will become visible once the view is touched. The ImageView containing the drawable will be then moved to the position that was touched and the ripple animation will start thereafter. Now, while trying to do this, I'm stumbling upon one thing which is I can't figure out how to find out the position that was touched. I came across several questions on stackoverflow which said that the touch position can be found out by using the following code.

@Override
public boolean onTouch(View v, MotionEvent e) {

      int X = (int)(e.getX());
      int Y = (int)(e.getY());

      return false;
}

I did try to implement this code in my app but I ended up with a NullPointerException. Please tell me how to find the exact location of the screen that was touched and move the view there?

Brandon
  • 29
  • 2
  • http://stackoverflow.com/questions/5002049/ontouchevent-vs-ontouch – Robert Rowntree Nov 16 '14 at 16:04
  • 1
    @Robert Rowntree What I understood from the link you gave me, that `onTouch` works both in Activities and Views but `onTouchEvent`works only in Views. Which means both of them are compatible to work with Views, then why am I getting the `NullPointerException`? – Brandon Nov 16 '14 at 19:24

2 Answers2

0

Use like this:

@Override
public boolean onTouch(View v, MotionEvent e) {
  if(e.getAction() == MotionEvent.ACTION_DOWN) { //ACTION_DOWN for the position touched.
    int X = (int)(e.getX());
    int Y = (int)(e.getY());
  }
  return false;
}
Mohammed Ali
  • 2,758
  • 5
  • 23
  • 41
0

You should get position for ACTION_DOWN event and then move your view

public boolean onTouchEvent(MotionEvent event) {
  switch (event.getAction()) {
     case MotionEvent.ACTION_DOWN:
          float x = event.getX();
          float y = event.getY();
          break;
    case MotionEvent.ACTION_MOVE:
        break;
    case MotionEvent.ACTION_UP:
        break;
}
return true;
}
Amar1989
  • 502
  • 1
  • 3
  • 17