在不干扰用户触摸事件的情况下为自定义视图使用触摸事件

Use touch event for custom view without interfering with the user's touch event

我为自定义视图创建了一个库。我使用 OnTouchListener() 来处理自定义触摸事件,但我希望用户能够设置自己的 OnTouchListener()。我该如何处理?!

您应该为自定义视图覆盖 onTouchEvent()

@Override
public boolean onTouchEvent(MotionEvent event) {
    Toast.makeText(this.getContext(), "Touched layout", Toast.LENGTH_SHORT).show();
    Log.d("TOUCH", "Touched layout");

    return super.onTouchEvent(event);
}

根据官方文档

onTouch() - This returns a boolean to indicate whether your listener consumes this event. The important thing is that this event can have multiple actions that follow each other. So, if you return false when the down action event is received, you indicate that you have not consumed the event and are also not interested in subsequent actions from this event. Thus, you will not be called for any other actions within the event, such as a finger gesture, or the eventual up action event.