Android 回调机制

Android 回调机制

在android开发中经常遇到各种各样的回调方法,然而,到底什么是回调呢?
现在,以android中View的onClick()回调方法为例,讲解一下。

OnClickListener 接口,当view被点击后回调该接口
 /** * 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. */
        void onClick(View v);
    }
在Activity中实现回调接口
public class MainActivity extends Activity implements OnClickListener {
    Button btn_location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_location = (Button) findViewById(R.id.btn_location);
        btn_location.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //TODO action
            }
        });
    }
}
View 类 当View被点击后,注册一个回调接口,用于调用。
public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
    /** * Listener used to dispatch click events. * This field should be made private, so it is hidden from the SDK. * {@hide} */
        public OnClickListener mOnClickListener;

    /** * 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(OnClickListener l) {
        if (!isClickable()) {
            setClickable(true);
        }
        getListenerInfo().mOnClickListener = l;
    }

     /** * Call this view's OnClickListener, if it is defined. Performs all normal * actions associated with clicking: reporting accessibility event, playing * a sound, etc. * * @return True there was an assigned OnClickListener that was called, false * otherwise is returned. */
    public boolean performClick() {
        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);

        ListenerInfo li = mListenerInfo;
        if (li != null && li.mOnClickListener != null) {
            playSoundEffect(SoundEffectConstants.CLICK);
            li.mOnClickListener.onClick(this);
            return true;
        }

        return false;
    }
}

你可能感兴趣的:(android,callback,回调机制)