Android onTouch with onClick and onLongClick

后端 未结 1 1820
青春惊慌失措
青春惊慌失措 2021-01-12 07:36

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

相关标签:
1条回答
  • 2021-01-12 07:57

    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;
    }
    
    0 讨论(0)
提交回复
热议问题