ImageView click best practice

I am a newbie in Andoird.

In my case, I have a scenario that when click certain part of an image it will trigger onclick events. I tried to detecte the position when the onTouch is fired, it works, but I think it's not a standard implementation, so what is the best practice for such case?


here is codes like:

imgView.setOnTouchListener((OnTouchListener) new OnTouchListener(){

public boolean onTouch(View v, MotionEvent event) { 
    if(isIn(event.getX(), event.getY(), 124,3,221,36)){ 
    } else if(isIn(event.getX(), event.getY(), 8,155,72,181)){
    return true; 
private boolean isIn(float x, float y, int fx, int fy, int tx, int ty) { 
    return x<tx && x > fx && y<ty && y>fy; 


Try to use ImageButton

Simply implement onClickListener() for your ImageView.

Easiest way to implement onClick event is to include android:onClickMe="methodName" inside your <ImageView> in XML layout and define that method inside your activity file.

For example:

public void methodName(View v)

   // do whatever you want for click even ton imageview

If you want to detect the position where user touched(Relative to the ImageView user touched), you can get the touch point from MotionEvent object.

Try to register a touch event listener for the ImageView and get the touched point position from MotionEvent object's getX() and getY() methods when touch event is triggered. And then define a rectangular area and using contains() to check whether the touch point is inside the area or not.

ImageView img = new ImageView(this);
img.setOnTouchListener(new OnTouchListener(){

    public boolean onTouch(View v, MotionEvent event) {
        Log.w("Hit test", "is hit? "+isIn(event.getX(),event.getY(),0,0,120,120));
        return false;


private boolean isIn(float x, float y, int fx, int fy, int tx, int ty){
    return new Rect(fx,fy,tx,ty).contains((int)x,(int)y);

Hope this will be helpful to you. :)

Need Your Help

(Mac) -bash: __git_ps1: command not found

macos git terminal ps1

I'm trying to change my command promt in terminal. I keep getting the error:

Misra standard for embedded software

c code-analysis embedded misra

I have a requirement to make a large amount of code MISRA compliant.