setOnClickListener是Android开发中常用的点击事件监听器,多用于页面按钮调用。它的实现方法比较特殊,是通过回调实现的。下面看看它的源码
* Register a callback to be invoked when this view is clicked. If this view is not * clickable, it becomes clickable. * @param l The callback that will run * @see #setClickable(boolean) public void setOnClickListener(@Nullable OnClickListener l) { getListenerInfo().mOnClickListener = l;
可以看到该控件是继承自View.java类, 在调用时传入一个setOnClickListener对象作为参数,该对象是一个接口类型的,其源码如下:
* Interface definition for a callback to be invoked when a view is clicked. public interface OnClickListener { * Called when a view has been clicked. * @param v The view that was clicked.
在OnClickListener接口中声明了一个onClick方法,需要我们在调用时实现。通过实践可以发现,当你传入了一个new View.OnClickListener()的参数时,Android Studio会自动补全onClick(View v)方法并让你去实现。在实现了onClick()方法后,它会在View的某个地方被调用,这就是回调的流程。下面是view中具体执行代码:
* Call this view's OnClickListener, if it is defined. Performs all normal * actions associated with clicking: reporting accessibility event, playing * @return True there was an assigned OnClickListener that was called, false // NOTE: other methods on View should not call this method directly, but performClickInternal() // instead, to guarantee that the autofill manager is notified when necessary (as subclasses // could extend this method without calling super.performClick()). public boolean performClick() { // We still need to call this method to handle the cases where performClick() was called // externally, instead of through performClickInternal() notifyAutofillManagerOnClick(); final ListenerInfo li = mListenerInfo; if (li != null && li.mOnClickListener != null) { playSoundEffect(SoundEffectConstants.CLICK); li.mOnClickListener.onClick(this); sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); notifyEnterOrExitForAutoFillIfNeeded(true);
该方法调用了onClick()
|