》However, extending every View object in order to handle such an event would not be practical. This is why the View class also contains a collection of nested interfaces with callbacks that you can much more easily define. These interfaces, called event listeners, are your ticket to capturing the user interaction with your UI.
接口回调:An event listener is an interface in the View
class that contains a single callback method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI.
》These methods are the sole inhabitants of their respective interface. To define one of these methods and handle your events, implement the nested interface in your Activity or define it as an anonymous class.
Remember that hardware key events are always delivered to the View currently in focus. They are dispatched starting from the top of the View hierarchy, and then down, until they reach the appropriate destination. If your View (or a child of your View) currently has focus, then you can see the event travel through the
method. As an alternative to capturing key events through your View, you can also receive all of the events inside your Activity with dispatchKeyEvent()
and onKeyDown()
.onKeyUp()
》事件响应优先级, Note: Android will call event handlers first and then the appropriate default handlers from the class definition second. As such, returning true from these event listeners will stop the propagation of the event to other event listeners and will also block the callback to the default event handler in the View. So be certain that you want to terminate the event when you return true.
》In the document about Custom Components, you'll learn see some of the common callbacks used for event handling, including:
- Called when a new key event occurs.onKeyDown(int, KeyEvent)
- Called when a key up event occurs.onKeyUp(int, KeyEvent)
- Called when a trackball motion event occurs.onTrackballEvent(MotionEvent)
- Called when a touch screen motion event occurs.onTouchEvent(MotionEvent)
- Called when the view gains or loses focus.onFocusChanged(boolean, int, Rect)
So, when managing more complex events inside a layout, consider these other methods:
- This allows yourActivity.dispatchTouchEvent(MotionEvent)
Activity
to intercept all touch events before they are dispatched to the window.
- This allows aViewGroup.onInterceptTouchEvent(MotionEvent)
ViewGroup
to watch events as they are dispatched to child Views.
- Call this upon a parent View to indicate that it should not intercept touch events withViewParent.requestDisallowInterceptTouchEvent(boolean)
.onInterceptTouchEvent(MotionEvent)