Skip to content Skip to sidebar Skip to footer

Android Ontouch With Onclick And Onlongclick

I've got a custom view which acts like a button. I want to change the background when user press it, revert the background to original when user moves the finger outside or release

Solution 1:

onClick & onLongClick is actually dispatched from View.onTouchEvent.

if you override View.onTouchEvent or set some specific View.OnTouchListener via setOnTouchListener, you must care for that.

so your code should be something like:

public boolean onTouch(View v, MotionEvent evt)
{
  // to dispatch click / long click event,
  // you must pass the event to it's default callback View.onTouchEvent
  boolean defaultResult = v.onTouchEvent(evt);

  switch (evt.getAction())
  {
    case MotionEvent.ACTION_DOWN:
    {
      setSelection(true); // just changing the background
      break;
    }
    case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_OUTSIDE:
    {
      setSelection(false); // just changing the background
      break;
    }
    default:
      return defaultResult;
  }

  // if you reach here, you have consumed the event
  return true;
}

Post a Comment for "Android Ontouch With Onclick And Onlongclick"