Detecting the location where a button was clicked

60 views Asked by At

I was wondering if there is a way to know exactly where a button was tapped, and take different actions based on where the user tapped it. Something like:

fooBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        switch(onClickLocation){
            case LEFT:
                foo();
                break;
            case RIGHT:
                bar();
                break;
            case MIDDLE:
                baz();
                break;
        }
    }
});
1

There are 1 answers

4
CommonsWare On

Not using an OnClickListener. OnTouchListener gives you a MotionEvent that you can use to determine where the actual touch event occurred.

For example, here I register both an OnClickListener and an OnTouchListener on the same View (called row):

row.setOnClickListener(this);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  row.setOnTouchListener(new View.OnTouchListener() {
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean onTouch(View v, MotionEvent event) {
      v
        .findViewById(R.id.row_content)
        .getBackground()
        .setHotspot(event.getX(), event.getY());

      return(false);
    }
  });
}

In this case, I don't need to know where the widget was touched for processing the click, but I do need to know where the widget was touched for adjusting the RippleDrawable background, so the ripple appears to emanate from where the user touched. Returning false from onTouch() means I am not consuming the touch event, and so eventually my onClick() method will also be called.

In your case, either:

  • do the actual work in onTouch(), or

  • cache the last-seen touch point in onTouch() but do not do the work until onClick()

My gut tells me that the latter should give you better results (e.g., you won't misinterpret a long-click), but I have not tried doing what you are seeking.