how to get touch coordinates with respect to a parent view in android

1.5k Views Asked by At

I have two images:

  1. a circle
  2. a small triangle placed on top of the circle.

These two images are placed inside a fragment. I have a touch listener for the triangle. But i want to calculate the coordinates of the touch and subsequent movement based on the circle, as i have to move the triangle along the cirle.

Is there a way to get the find the touch coordinates with respect to the fragment so that all the calculations are relative to the fragment?

UPDATE: THE reason I would to find these coordinates is because i have to move the triangle image along the edge of the circle image. So i need to calculate the distance of the touch movement from the circle image and then move the triangle along the circle till the touch coordinates are almost the same as the radius of the circle. And stop moving if the touch event moves somewhere else.

I have the following code to calculate the distance of the touch from the centre of the circle and move the triangle only if this value is almost the same as that of the radius.

public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {

                case MotionEvent.ACTION_DOWN:





                        float touchPosRelativeToCircleX = event.getX() + mCurrTempIndicator.getLeft() - mThermostatBgrd.getLeft();
                        float touchPosRelativeToCircleY = event.getY() + mCurrTempIndicator.getTop() - mThermostatBgrd.getTop();


                        float dx = touchPosRelativeToCircleX;
                        float dy = touchPosRelativeToCircleY;

                        float r = FloatMath.sqrt((dx * dx) + (dy * dy));


                    break;

                case MotionEvent.ACTION_MOVE:


                    dx = event.getX() + mCurrTempIndicator.getLeft() - mThermostatBgrd.getLeft();
                    dy = event.getY() + mCurrTempIndicator.getTop() - mThermostatBgrd.getTop();

                    r = FloatMath.sqrt((dx * dx) + (dy * dy));

                    // if r is almost the same as  the radius them move else don't move.


                break;

                case MotionEvent.ACTION_UP:
                    allowRotating = true;
                    break;
            }



            return true;
        }
2

There are 2 best solutions below

0
On

Set an onTouchListener on the rootView of fragment. When you touch over the triangle, you will also touch view of the fragment and you'll get the callback.

3
On

In your triangle view's on touch listener's onTouch call back, do:

touchPosRelativeToCircleX = event.getX() + triangleView.getLeft() - circleView.getLeft();
touchPosRelativeToCircleY = event.getY() + triangleView.getTop() - circleView.getTop();