Class A实现接口CallBack callback——背景1 class A中包含一个class B的引用b——背景2 class B有一个参数为callback的方法f(CallBack callback)——背景3 A的对象a调用B的方法 f(CallBack callback) ——A类调用B类的某个方法 C 然后b就可以在f(CallBack callback)方法中调用A的方法 ——B类调用A类的某个方法D 大家都喜欢用打电话的例子,好吧,为了跟上时代,我也用这个例子好了,我这个例子采用异步加回调
//这个是View的一个回调接口 publicinterfaceOnClickListener{ /** * Called when a view has been clicked. * * @param v The view that was clicked. */ voidonClick(View v); }
/** * 这个View就相当于B类 * @author xiaanming * */ publicclassViewimplementsDrawable.Callback, KeyEvent.Callback, AccessibilityEventSource{ /** * Listener used to dispatch click events. * This field should be made private, so it is hidden from the SDK. * {@hide} */ protected OnClickListener mOnClickListener; /** * setOnClickListener()的参数是OnClickListener接口------>背景三 * 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) */ publicvoidsetOnClickListener(OnClickListener l){ if (!isClickable()) { setClickable(true); } mOnClickListener = l; } /** * Call this view's OnClickListener, if it is defined. * * @return True there was an assigned OnClickListener that was called, false * otherwise is returned. */ publicbooleanperformClick(){ sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); if (mOnClickListener != null) { playSoundEffect(SoundEffectConstants.CLICK); //这个不就是相当于B类调用A类的某个方法D,这个D就是所谓的回调方法咯 mOnClickListener.onClick(this); returntrue; } returnfalse; } }