0

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?

thanks.

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)){ 
        ShowMemberInfo(R.string.app_m01); 
    } 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; 
}
SICON
  • 65
  • 1
  • 10
  • can you show us your implementation so we can know if it's or it isn't a standard implementation or if there is a best practice? – Th0rndike Apr 12 '12 at 08:40
  • I had modified my answer. :) Maybe you can try to use Rect to define your custom detect region and call contains() to check whether the touch point is inside the area or not. – Chickenrice Apr 13 '12 at 04:19

3 Answers3

0

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
}
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
0

Try to use ImageButton

Bakyt
  • 1,268
  • 11
  • 10
  • this, this is really helpful... Below link may be a better approach... [link](http://stackoverflow.com/questions/10137657/onclicklistener-issues-after-imagebutton-moved-after-translateanimation) – SICON Apr 16 '12 at 02:43
0

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(){

    @Override
    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. :)

Chickenrice
  • 5,727
  • 2
  • 22
  • 21