Search code examples
androidimagemappingareaclickable

Android - create clickable area on imageview


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.


Solution

  • 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];