標籤:on() sig 舉例 define ted init 代碼 long pack
現在來分析分析下Android View的點擊方法onclick();我們知道onclick()是一個回調方法,當使用者點擊View就執行這個方法,我們用Button來舉例好了 //這個是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);} package com.example.demoactivity; import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast; /*** 這個就相當於Class A* @author xiaanming* 實現了 OnClickListener介面---->背景一*/public class MainActivity extends Activity implements OnClickListener{/*** Class A 包含Class B的引用----->背景二*/private Button button; @Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button = (Button)findViewById(R.id.button1); /*** Class A 調用View的方法,而Button extends View----->A類調用B類的某個方法 C*/button.setOnClickListener(this);} /*** 使用者點擊Button時調用的回呼函數,你可以做你要做的事* 這裡我做的是用Toast提示OnClick*/@Overridepublic void onClick(View v) {Toast.makeText(getApplication(), "OnClick", Toast.LENGTH_LONG).show();} } 下面是View類的setOnClickListener方法,就相當於B類咯,只把關鍵代碼貼出來/*** 這個View就相當於B類* @author xiaanming**/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}*/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)*/ public void setOnClickListener(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.*/public boolean performClick() {sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); if (mOnClickListener != null) {playSoundEffect(SoundEffectConstants.CLICK); //這個不就是相當於B類調用A類的某個方法D,這個D就是所謂的回調方法咯mOnClickListener.onClick(this);return true;} return false;}} 這個例子就是Android典型的回調機制,看完這個你是不是更進一步的理解了回調機制呢? 線程run()也是一個回調方法,當執行Thread的start()方法就會回調這個run()方法,還有處理訊息都比較經典等等
回調深入理解 同步回調 以android中View.OnClickListener為列