user1472757
user1472757

Reputation: 133

Finding co-ordinates inside an imageview?

Im trying to find the co-ordinates were a user is touching inside an imageview only.

So far i have managed to do this by the following code:

    img = (ImageView) findViewById(R.id.image);
    img.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            x = (int) event.getX();
            y = (int) event.getY();
            int[] viewCoords = new int[2];
            img.getLocationOnScreen(viewCoords);
            int imageX = (int) (x - viewCoords[0]); // viewCoods[0] is the X coordinate
            int imageY = (int) (y - viewCoords[1]); // viewCoods[1] is the y coordinate
            text.setText("x:" +x +"y"+y);

            return false;
        }
    });

However this is onTouchListener which means it only finds the co-ordinates after each touch, what i want to do is create it so that it constantly finds co-ordinates while the user moves their finger around the imageview. I achieved this for the whole screen by this code:

@Override
public boolean onTouchEvent(MotionEvent event) {
    x = (float)event.getX();
    y = (float)event.getY();
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_UP:
    }



    text.setText("x:"+ x +" y:" +y);

return false;
}

However I don't know how to make this code work inside the imageview only.

enter image description here

Upvotes: 0

Views: 232

Answers (1)

Tim
Tim

Reputation: 35933

Your problem is that you return false at the end of the onTouch event.

When you return false, you are telling the OS that you are no longer interested in any events related to this particular gesture, so it stops informing your view of future activity (such as ACTION_MOVE and ACTION_UP).

Return true to onTouchEvent, and you will continue to receive a stream of events as long as the finger is held to the screen, and a final event when it is released.

Upvotes: 2

Related Questions