0

I'm trying to develop an android application similar to "on color measurement" or "color grab" which are already on google play. I have problem with getting the exact position of a view (which acts like focus square) and move it to the position where the user touches the screen. I have done a lot of searches but all of them ended in onTouchEvent() which I used it but it does not work properly or maybe I have done something wrong. Actually the view moves but it won't be placed exactly where the user touch, it will go below the touched area in y axis with a distance.

here is my code where the mFocusRectangle is the custom view which I want to move to the touched position:

@Override
public boolean onTouchEvent(MotionEvent event) {

    int action = event.getAction();
if (event.getPointerCount() > 1) {
        // handle multi-touch events

    } else {
        // handle single touch events
        if(action==MotionEvent.ACTION_DOWN){

        }
        if (action == MotionEvent.ACTION_UP) {
            int pointerId = event.getPointerId(0);
            int pointerIndex = event.findPointerIndex(pointerId);
            // Get the pointer's current position
            float x = event.getX(pointerIndex);
            float y = event.getY(pointerIndex);
            mFocusRectangle.showStart();
            mFocusRectangle.setX(x);
            mFocusRectangle.setY(y);

        }
    }
    return true;
}

I have also tried MotionEvent.ACTION_DOWN but the result is the same. Thanks in advance.

elahe
  • 11
  • 3

1 Answers1

0

try this

float x = event.getX(pointerIndex) - (mFocusRectangle.getWidth() / 2);
float y = event.getY(pointerIndex) - (mFocusRectangle.getHeight() / 2);

credits: Manitoba - Android move view on touch event

Community
  • 1
  • 1
The Badak
  • 2,010
  • 2
  • 16
  • 28