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

Keep priority after update with AngularFire

firebase angularfire

I have a database with exercises, and each exercise has a field userId which references to the user that the exercise belongs to. I would want to retrieve every exercise that belongs to the current...

how to store an array in jquery cookie?

jquery arrays cookies

I need to store an array in a jQuery cookie, any one help me please?