浅谈setOnClickListener使用方法

setOnClickListener是Android开发中常用的点击事件监听器,多用于页面按钮调用。它的实现方法比较特殊,是通过回调实现的。下面看看它的源码

  1. /**
  2. * Register a callback to be invoked when this view is clicked. If this view is not
  3. * clickable, it becomes clickable.
  4. *
  5. * @param l The callback that will run
  6. *
  7. * @see #setClickable(boolean)
  8. */
  9. public void setOnClickListener(@Nullable OnClickListener l) {
  10. if (!isClickable()) {
  11. setClickable(true);
  12. }
  13. getListenerInfo().mOnClickListener = l;
  14. }

可以看到该控件是继承自View.java类, 在调用时传入一个setOnClickListener对象作为参数,该对象是一个接口类型的,其源码如下:

  1. /**
  2. * Interface definition for a callback to be invoked when a view is clicked.
  3. */
  4. public interface OnClickListener {
  5. /**
  6. * Called when a view has been clicked.
  7. *
  8. * @param v The view that was clicked.
  9. */
  10. void onClick(View v);
  11. }

在OnClickListener接口中声明了一个onClick方法,需要我们在调用时实现。通过实践可以发现,当你传入了一个new View.OnClickListener()的参数时,Android Studio会自动补全onClick(View v)方法并让你去实现。在实现了onClick()方法后,它会在View的某个地方被调用,这就是回调的流程。下面是view中具体执行代码:

  1. /**
  2. * Call this view's OnClickListener, if it is defined. Performs all normal
  3. * actions associated with clicking: reporting accessibility event, playing
  4. * a sound, etc.
  5. *
  6. * @return True there was an assigned OnClickListener that was called, false
  7. * otherwise is returned.
  8. */
  9. // NOTE: other methods on View should not call this method directly, but performClickInternal()
  10. // instead, to guarantee that the autofill manager is notified when necessary (as subclasses
  11. // could extend this method without calling super.performClick()).
  12. public boolean performClick() {
  13. // We still need to call this method to handle the cases where performClick() was called
  14. // externally, instead of through performClickInternal()
  15. notifyAutofillManagerOnClick();
  16. final boolean result;
  17. final ListenerInfo li = mListenerInfo;
  18. if (li != null && li.mOnClickListener != null) {
  19. playSoundEffect(SoundEffectConstants.CLICK);
  20. li.mOnClickListener.onClick(this);
  21. result = true;
  22. } else {
  23. result = false;
  24. }
  25. sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
  26. notifyEnterOrExitForAutoFillIfNeeded(true);
  27. return result;
  28. }

该方法调用了onClick()

(0)

相关推荐