4

I want to create a clickable area on imageview using this data

"X1": "213",
"Y1": "174",
"X2": "339",
"Y2": "269",

and also I want to associate a Action with this clickable area like go to some Activity when tap on it. I don't want to use solution given in this link. clickable area of image

Because I have multiple Imageviews and coordinates can be different every time. These ordinates are coming from server.

please suggest the best way to handle this problem.

Community
  • 1
  • 1
Hamza Mehmood
  • 151
  • 1
  • 10
  • You can create RectF object with provided coordinates and use onTouchListner to imageview and compare your rectf with clicked area. – USKMobility Apr 25 '16 at 10:05
  • You could try to use Rectangles (`Rect()`), a `onTouchListener()` for the whole layout, and check if the event coordinates are within your rectangle. There is also a Layout called [`AbsoluteLayout`](http://developer.android.com/reference/android/widget/AbsoluteLayout.html), where you can specify exact locations, which I do not recommend, since you don't support different screen sizes if you use it. – yennsarah Apr 25 '16 at 10:06
  • Will Rectangles (Rect()) also scale my given ordinates according to the screen size? as my imageview is match_parent in width and wrap_content in height? – Hamza Mehmood Apr 25 '16 at 10:10
  • because Server is giving these ordinates for a image with width 640px and height 380px. – Hamza Mehmood Apr 25 '16 at 10:12

1 Answers1

7

You can watch the touched locations:

ImageView iv = (ImageView) findViewById(R.id.image);
iv.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
    log.d(TAG,"Location: " + event.getX() + " , " + event.getY());
    }
});

UPDATE 1: You can have the top-left location of your view as follow:

int[] viewCoords = new int[2];
imageView.getLocationOnScreen(viewCoords);

From there, you can see the exact location of your image view that get touched:

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

int imageX = X - viewCoords[0];
int imageY = Y - viewCoords[1];
Mohammad Zarei
  • 1,773
  • 14
  • 33