Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android View 事件分發機制 源碼解析 (上)

Android View 事件分發機制 源碼解析 (上)

編輯:關於Android編程

一直想寫事件分發機制的文章,不管咋樣,也得自己研究下事件分發的源碼,寫出心得~

首先我們先寫個簡單的例子來測試View的事件轉發的流程~

1、案例

為了更好的研究View的事件轉發,我們自定以一個MyButton繼承Button,然後把跟事件傳播有關的方法進行復寫,然後添加上日志~

MyButton

package com.example.zhy_event03;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Button;

public class MyButton extends Button
{
	private static final String TAG = MyButton.class.getSimpleName();

	public MyButton(Context context, AttributeSet attrs)
	{
		super(context, attrs);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		int action = event.getAction();

		switch (action)
		{
		case MotionEvent.ACTION_DOWN:
			Log.e(TAG, "onTouchEvent ACTION_DOWN");
			break;
		case MotionEvent.ACTION_MOVE:
			Log.e(TAG, "onTouchEvent ACTION_MOVE");
			break;
		case MotionEvent.ACTION_UP:
			Log.e(TAG, "onTouchEvent ACTION_UP");
			break;
		default:
			break;
		}
		return super.onTouchEvent(event);
	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent event)
	{
		int action = event.getAction();

		switch (action)
		{
		case MotionEvent.ACTION_DOWN:
			Log.e(TAG, "dispatchTouchEvent ACTION_DOWN");
			break;
		case MotionEvent.ACTION_MOVE:
			Log.e(TAG, "dispatchTouchEvent ACTION_MOVE");
			break;
		case MotionEvent.ACTION_UP:
			Log.e(TAG, "dispatchTouchEvent ACTION_UP");
			break;

		default:
			break;
		}
		return super.dispatchTouchEvent(event);
	}

	
}

在onTouchEvent和dispatchTouchEvent中打印了日志~

然後把我們自定義的按鈕加到主布局文件中;

布局文件:



    



最後看一眼MainActivity的代碼

package com.example.zhy_event03;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class MainActivity extends Activity
{
	protected static final String TAG = "MyButton";
	private Button mButton ;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mButton = (Button) findViewById(R.id.id_btn);
		mButton.setOnTouchListener(new OnTouchListener()
		{
			@Override
			public boolean onTouch(View v, MotionEvent event)
			{
				int action = event.getAction();

				switch (action)
				{
				case MotionEvent.ACTION_DOWN:
					Log.e(TAG, "onTouch ACTION_DOWN");
					break;
				case MotionEvent.ACTION_MOVE:
					Log.e(TAG, "onTouch ACTION_MOVE");
					break;
				case MotionEvent.ACTION_UP:
					Log.e(TAG, "onTouch ACTION_UP");
					break;
				default:
					break;
				}
				
				return false;
			}
		});
	}

	
}

在MainActivity中,我們還給MyButton設置了OnTouchListener這個監聽~

好了,跟View事件相關一般就這三個地方了,一個onTouchEvent,一個dispatchTouchEvent,一個setOnTouchListener;

下面我們運行,然後點擊按鈕,查看日志輸出:

08-31 06:09:39.030: E/MyButton(879): dispatchTouchEvent ACTION_DOWN
08-31 06:09:39.030: E/MyButton(879): onTouch ACTION_DOWN
08-31 06:09:39.049: E/MyButton(879): onTouchEvent ACTION_DOWN
08-31 06:09:39.138: E/MyButton(879): dispatchTouchEvent ACTION_MOVE
08-31 06:09:39.138: E/MyButton(879): onTouch ACTION_MOVE
08-31 06:09:39.147: E/MyButton(879): onTouchEvent ACTION_MOVE
08-31 06:09:39.232: E/MyButton(879): dispatchTouchEvent ACTION_UP
08-31 06:09:39.248: E/MyButton(879): onTouch ACTION_UP
08-31 06:09:39.248: E/MyButton(879): onTouchEvent ACTION_UP

我有意點擊的時候蹭了一下,不然不會觸發MOVE,手抖可能會打印一堆MOVE的日志~~~

好了,可以看到,不管是DOWN,MOVE,UP都會按照下面的順序執行:

1、dispatchTouchEvent

2、 setOnTouchListener的onTouch

3、onTouchEvent

下面就跟隨日志的腳步開始源碼的探索~

2、dispatchTouchEvent

首先進入View的dispatchTouchEvent

/**
     * Pass the touch screen motion event down to the target view, or this
     * view if it is the target.
     *
     * @param event The motion event to be dispatched.
     * @return True if the event was handled by the view, false otherwise.
     */
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (!onFilterTouchEventForSecurity(event)) {
            return false;
        }

        if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
                mOnTouchListener.onTouch(this, event)) {
            return true;
        }
        return onTouchEvent(event);
    }

直接看13行:首先判斷mOnTouchListener不為null,並且view是enable的狀態,然後 mOnTouchListener.onTouch(this, event)返回true,這三個條件如果都滿足,直接return true ; 也就是下面的onTouchEvent(event)不會被執行了;

那麼mOnTouchListener是和方神聖,我們來看看:

   /**
     * Register a callback to be invoked when a touch event is sent to this view.
     * @param l the touch listener to attach to this view
     */
    public void setOnTouchListener(OnTouchListener l) {
        mOnTouchListener = l;
    }
其實就是我們在Activity中設置的setOnTouchListener。

也就是說:如果我們設置了setOnTouchListener,並且return true,那麼View自己的onTouchEvent就不會被執行了,當然了,本例我們return false,我們還得往下探索 ;

已經解決一個常見的問題:View的onTouchListener和onTouchEvent的調用關系,相信大家應該已經明白了~let's go;繼續往下。

3、View的onTouchEvent:

接下來是View的onTouchEvent:

/**
     * Implement this method to handle touch screen motion events.
     *
     * @param event The motion event.
     * @return True if the event was handled, false otherwise.
     */
    public boolean onTouchEvent(MotionEvent event) {
        final int viewFlags = mViewFlags;

        if ((viewFlags & ENABLED_MASK) == DISABLED) {
            // A disabled view that is clickable still consumes the touch
            // events, it just doesn't respond to them.
            return (((viewFlags & CLICKABLE) == CLICKABLE ||
                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
        }

        if (mTouchDelegate != null) {
            if (mTouchDelegate.onTouchEvent(event)) {
                return true;
            }
        }

        if (((viewFlags & CLICKABLE) == CLICKABLE ||
                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_UP:
                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
                        // take focus if we don't have it already and we should in
                        // touch mode.
                        boolean focusTaken = false;
                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
                            focusTaken = requestFocus();
                        }

                        if (!mHasPerformedLongPress) {
                            // This is a tap, so remove the longpress check
                            removeLongPressCallback();

                            // Only perform take click actions if we were in the pressed state
                            if (!focusTaken) {
                                // Use a Runnable and post this rather than calling
                                // performClick directly. This lets other visual state
                                // of the view update before click actions start.
                                if (mPerformClick == null) {
                                    mPerformClick = new PerformClick();
                                }
                                if (!post(mPerformClick)) {
                                    performClick();
                                }
                            }
                        }

                        if (mUnsetPressedState == null) {
                            mUnsetPressedState = new UnsetPressedState();
                        }

                        if (prepressed) {
                            mPrivateFlags |= PRESSED;
                            refreshDrawableState();
                            postDelayed(mUnsetPressedState,
                                    ViewConfiguration.getPressedStateDuration());
                        } else if (!post(mUnsetPressedState)) {
                            // If the post failed, unpress right now
                            mUnsetPressedState.run();
                        }
                        removeTapCallback();
                    }
                    break;

                case MotionEvent.ACTION_DOWN:
                    if (mPendingCheckForTap == null) {
                        mPendingCheckForTap = new CheckForTap();
                    }
                    mPrivateFlags |= PREPRESSED;
                    mHasPerformedLongPress = false;
                    postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
                    break;

                case MotionEvent.ACTION_CANCEL:
                    mPrivateFlags &= ~PRESSED;
                    refreshDrawableState();
                    removeTapCallback();
                    break;

                case MotionEvent.ACTION_MOVE:
                    final int x = (int) event.getX();
                    final int y = (int) event.getY();

                    // Be lenient about moving outside of buttons
                    int slop = mTouchSlop;
                    if ((x < 0 - slop) || (x >= getWidth() + slop) ||
                            (y < 0 - slop) || (y >= getHeight() + slop)) {
                        // Outside button
                        removeTapCallback();
                        if ((mPrivateFlags & PRESSED) != 0) {
                            // Remove any future long press/tap checks
                            removeLongPressCallback();

                            // Need to switch from pressed to not pressed
                            mPrivateFlags &= ~PRESSED;
                            refreshDrawableState();
                        }
                    }
                    break;
            }
            return true;
        }

        return false;
    }

代碼還是比較長的,

10-15行,如果當前View是Disabled狀態且是可點擊則會消費掉事件(return true);可以忽略,不是我們的重點;

17-21行,如果設置了mTouchDelegate,則會將事件交給代理者處理,直接return true,如果大家希望自己的View增加它的touch范圍,可以嘗試使用TouchDelegate,這裡也不是重點,可以忽略;

接下來到我們的重點了:

23行的判斷:如果我們的View可以點擊或者可以長按,則,注意IF的范圍,最終一定return true ;

if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
//...
return true;
}

接下來就是 switch (event.getAction())了,判斷事件類型,DOWN,MOVE,UP等;

我們按照例子執行的順序,先看 case MotionEvent.ACTION_DOWN (71-78行):

1、MotionEvent.ACTION_DOWN

75行:給mPrivateFlags設置一個PREPRESSED的標識

76行:設置mHasPerformedLongPress=false;表示長按事件還未觸發;

77行:發送一個延遲為ViewConfiguration.getTapTimeout()的延遲消息,到達延時時間後會執行CheckForTap()裡面的run方法:

1、ViewConfiguration.getTapTimeout()為115毫秒;

2、CheckForTap

  private final class CheckForTap implements Runnable {
        public void run() {
            mPrivateFlags &= ~PREPRESSED;
            mPrivateFlags |= PRESSED;
            refreshDrawableState();
            if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
                postCheckForLongClick(ViewConfiguration.getTapTimeout());
            }
        }
    }

在run方法裡面取消mPrivateFlags的PREPRESSED,然後設置PRESSED標識,刷新背景,如果View支持長按事件,則再發一個延時消息,檢測長按;

 private void postCheckForLongClick(int delayOffset) {
        mHasPerformedLongPress = false;

        if (mPendingCheckForLongPress == null) {
            mPendingCheckForLongPress = new CheckForLongPress();
        }
        mPendingCheckForLongPress.rememberWindowAttachCount();
        postDelayed(mPendingCheckForLongPress,
                ViewConfiguration.getLongPressTimeout() - delayOffset);
    }

class CheckForLongPress implements Runnable {

        private int mOriginalWindowAttachCount;

        public void run() {
            if (isPressed() && (mParent != null)
                    && mOriginalWindowAttachCount == mWindowAttachCount) {
                if (performLongClick()) {
                    mHasPerformedLongPress = true;
                }
            }
        }

可以看到,當用戶按下,首先會設置標識為PREPRESSED,如果在115毫秒內抬起了,UP時會移除CheckForTap這個回調(UP時會分析);

如果115後,沒有抬起,會將View的標識設置為PRESSED且去掉PREPRESSED標識,然後發出一個檢測長按的延遲任務,延時為:ViewConfiguration.getLongPressTimeout() - delayOffset(500ms -115ms),這個115ms剛好時檢測額PREPRESSED時間;也就是用戶從DOWN觸發開始算起,如果500ms內沒有抬起則認為觸發了長按事件:

1、如果此時設置了長按的回調,則執行長按時的回調,且如果長按的回調返回true;才把mHasPerformedLongPress置為ture;

2、否則,如果沒有設置長按回調或者長按回調返回的是false;則mHasPerformedLongPress依然是false;

好了DOWN就分析完成了;大家回個神,下面回到VIEW的onTouchEvent中的ACTION_MOVE:

2、MotionEvent.ACTION_MOVE

86到105行:

87-88行:拿到當前觸摸的x,y坐標;

91行判斷當然觸摸點有沒有移出我們的View,如果移出了:

1、執行removeTapCallback();

2、然後判斷是否包含PRESSED標識,如果包含,移除長按的檢查:removeLongPressCallback();

3、最後把mPrivateFlags中PRESSED標識去除,刷新背景;

 private void removeTapCallback() {
        if (mPendingCheckForTap != null) {
            mPrivateFlags &= ~PREPRESSED;
            removeCallbacks(mPendingCheckForTap);
        }
    }
這個是移除,DOWN觸發時設置的PREPRESSED的檢測;即當前觸發時機在DOWN觸發不到115ms時,你就已經移出控件外了;

如果115ms後,你才移出控件外,則你的當前mPrivateFlags一定為PRESSED且發送了長按的檢測;

就會走上面的2和3;首先移除removeLongPressCallback()
private void removeLongPressCallback() {
if (mPendingCheckForLongPress != null) {
removeCallbacks(mPendingCheckForLongPress);
}
}

然後把mPrivateFlags中PRESSED標識去除,刷新背景;

好了,MOVE我們也分析完成了,總結一下:只要用戶移出了我們的控件:則將mPrivateFlags取出PRESSED標識,且移除所有在DOWN中設置的檢測,長按等;

下面再回個神,回到View的onTouchEvent的ACTION_UP:

3、MotionEvent.ACTION_UP

26到69行:

27行:判斷mPrivateFlags是否包含PREPRESSED

28行:如果包含PRESSED或者PREPRESSED則進入執行體,也就是無論是115ms內或者之後抬起都會進入執行體。

36行:如果mHasPerformedLongPress沒有被執行,進入IF

38行:removeLongPressCallback();移除長按的檢測

45-50行:如果mPerformClick如果mPerformClick為null,初始化一個實例,然後立即通過handler添加到消息隊列尾部,如果添加失敗則直接執行 performClick();添加成功,在mPerformClick的run方法中就是執行performClick();

終於執行了我們的click事件了,下面看一下performClick()方法:

 public boolean performClick() {
        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);

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

        return false;
    }

if (mOnClickListener != null) {
mOnClickListener.onClick(this);
return true;
}

久違了~我們的mOnClickListener ;

別激動,還沒結束,回到ACTION_UP,

58行:如果prepressed為true,進入IF體:

為mPrivateFlags設置表示為PRESSED,刷新背景,125毫秒後執行mUnsetPressedState

否則:mUnsetPressedState.run();立即執行;也就是不管咋樣,最後mUnsetPressedState.run()都會執行;

看看這個UnsetPressedState主要干什麼:

private final class UnsetPressedState implements Runnable {
public void run() {
setPressed(false);
}
}

public void setPressed(boolean pressed) {
if (pressed) {
mPrivateFlags |= PRESSED;
} else {
mPrivateFlags &= ~PRESSED;
}
refreshDrawableState();
dispatchSetPressed(pressed);
}

把我們的mPrivateFlags中的PRESSED取消,然後刷新背景,把setPress轉發下去。

ACTION_UP的最後一行:removeTapCallback(),如果mPendingCheckForTap不為null,移除;

4、總結

好了,代碼跨度還是相當大的,下面需要總結下:

1、整個View的事件轉發流程是:

View.dispatchEvent->View.setOnTouchListener->View.onTouchEvent

在dispatchTouchEvent中會進行OnTouchListener的判斷,如果OnTouchListener不為null且返回true,則表示事件被消費,onTouchEvent不會被執行;否則執行onTouchEvent。

2、onTouchEvent中的DOWN,MOVE,UP

DOWN時:

a、首先設置標志為PREPRESSED,設置mHasPerformedLongPress=false ;然後發出一個115ms後的mPendingCheckForTap,如果115ms內抬起手指,觸發了UP,則不會觸發click事件,並且最終執行的是UnsetPressedState對象,setPressed(false)將setPress的傳遞下去;這種情況很少發生,可能只會在壓力測試的時候會發現無法觸發click事件;

b、如果115ms內沒有觸發UP,則將標志置為PRESSED,清除PREPRESSED標志,同時發出一個延時為500-115ms的,檢測長按任務消息;

c、如果500ms內(從DOWN觸發開始算),則會觸發LongClickListener:

此時如果LongClickListener不為null,則會執行回調,同時如果LongClickListener.onClick返回true,才把mHasPerformedLongPress設置為true;否則mHasPerformedLongPress依然為false;

MOVE時:

主要就是檢測用戶是否劃出控件,如果劃出了:

115ms內,直接移除mPendingCheckForTap;

115ms後,則將標志中的PRESSED去除,同時移除長按的檢查:removeLongPressCallback();

UP時:

a、如果115ms內,觸發UP,此時標志為PREPRESSED,則執行UnsetPressedState,setPressed(false);會把setPress轉發下去,可以在View中復寫dispatchSetPressed方法接收;

b、如果是115ms-500ms間,即長按還未發生,則首先移除長按檢測,執行onClick回調;

c、如果是500ms以後,那麼有兩種情況:

i.設置了onLongClickListener,且onLongClickListener.onClick返回true,則點擊事件OnClick事件無法觸發;

ii.沒有設置onLongClickListener或者onLongClickListener.onClick返回false,則點擊事件OnClick事件依然可以觸發;

d、最後執行mUnsetPressedState.run(),將setPressed傳遞下去,然後將PRESSED標識去除;


最後問個問題,然後再運行個例子結束:

1、setOnLongClickListener和setOnClickListener是否只能執行一個

不是的,只要setOnLongClickListener中的onClick返回false,則兩個都會執行;返回true則會屏幕setOnClickListener

最後我們給MyButton同時設置setOnClickListener和setOnLongClickListener,運行看看:

package com.example.zhy_event03;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity
{
	protected static final String TAG = "MyButton";
	private Button mButton ;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mButton = (Button) findViewById(R.id.id_btn);
		mButton.setOnTouchListener(new OnTouchListener()
		{
			@Override
			public boolean onTouch(View v, MotionEvent event)
			{
				int action = event.getAction();

				switch (action)
				{
				case MotionEvent.ACTION_DOWN:
					Log.e(TAG, "onTouch ACTION_DOWN");
					break;
				case MotionEvent.ACTION_MOVE:
					Log.e(TAG, "onTouch ACTION_MOVE");
					break;
				case MotionEvent.ACTION_UP:
					Log.e(TAG, "onTouch ACTION_UP");
					break;
				default:
					break;
				}
				
				return false;
			}
		});
		mButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Toast.makeText(getApplicationContext(), "onclick",Toast.LENGTH_SHORT).show();
			}
		});
		
		mButton.setOnLongClickListener(new OnLongClickListener()
		{
			@Override
			public boolean onLongClick(View v)
			{
				Toast.makeText(getApplicationContext(), "setOnLongClickListener",Toast.LENGTH_SHORT).show();
				return false;
			}
		});
	}

	
}
效果圖:


可以看到LongClickListener已經ClickListener都觸發了~


最後,本篇博文完成了對View的事件分發機制的整個流程的說明,並且對源碼進行了分析;










  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved