Android 觸控事件機制 一 簡介

2021-07-11 14:38:37 字數 2416 閱讀 8197

目錄

1. 觸控事件概述

2. activity, viewgroup, view中的觸控事件api

3. ontouchlistener介面

本文介紹的觸控事件api和介面主要是:dispatchtouchevent(), ontouchevent(), onintercepttouchevent()和ontouchlistener介面。這些內容中,最複雜的莫過於dispatchtouchevent(), ontouchevent()和onintercepttouchevent()這三者之間的關係。如果你能認真讀完本系列文章,相信對它們之間的關係,它們的原理和用法,很有很清晰的認識。

本文先對這些介面做個大致介紹,建立乙個整體概念。後續再通過閱讀activity, view和viewgroup中觸控事件api的原始碼,來對認識這些api;最後,再通過幾個示例來進一步了解它們,同時也了解它們的用法。

1. activity中的觸控事件api

public boolean dispatchtouchevent(motionevent ev);

public boolean ontouchevent(motionevent ev);

2. viewgroup中的觸控事件api

public boolean dispatchtouchevent(motionevent ev);

public boolean ontouchevent(motionevent ev);

public boolean onintercepttouchevent(motionevent ev);

3. view中的觸控事件api

public boolean dispatchtouchevent(motionevent ev);

public boolean ontouchevent(motionevent ev);

下面簡單的說明一下涉及到的三個api的作用。

dispatchtouchevent:它是傳遞觸控事件的介面。

(01) activity將觸控事件傳遞給viewgroup,viewgroup將觸控事件傳遞給另乙個viewgroup,以及viewgroup將觸控事件傳遞給view;這些都是通過dispatchtouchevent()來傳遞的。

(02) dispatchtouchevent(), onintercepttouchevent(), ontouchevent()以及ontouch()它們之間的聯絡,都是通過dispatchtouchevent()體現的。它們都是在dispatchtouchevent()中排程的!因此,理解dispatchtouchevent()是理解android事件機制的關機;而其中,最關機的就是viewgroup中的dispatchtouchevent()

(03) 返回值:true,表示觸控事件被消費了;false,則表示觸控事件沒有被消費。

ontouchevent:它是處理觸控事件的介面。

(01) 無論是activity, viewgroup還是view,對觸控事件的處理,基本上都是在ontouchevent()中進行的。因此,我們說它是處理觸控事件的介面。

(02) 返回值:返回true,表示觸控事件被它處理過了;或者,換句話說,表示它消費了觸控事件。否則,表示它沒有消費該觸控事件。

onintercepttouchevent:它是攔截觸控事件的介面。

(01) 只有viewgroup中才有該介面。如果viewgroup不想將觸控事件傳遞給它的子view,則可以在onintercepttouchevent中進行攔截。

(02) 返回值:true,表示viewgroup攔截了該觸控事件;那麼,該事件就不會分發給它的子view或者子viewgroup。否則,表示viewgroup沒有攔截該事件,該事件就會分發給它的子view和子viewgroup。

ontouchlistener乙個inte***ce介面,它是在view中宣告的。ontouchlistener中只包含了ontouch()函式。

那麼,ontouch()和ontouchevent()有什麼相同和不同點呢?

相同點ontouch()與ontouchevent()都是使用者處理觸控事件的api。

不同點(01),ontouch()是view專門提供給使用者的介面,目的是為了方便使用者自己處理觸控事件。而ontouchevent()是android系統自己實現的介面。

(02),ontouch()的優先順序比ontouchevent()的優先順序更高。

dispatchtouchevent()中分發事件的時候,會先將事件分配給ontouch()進行處理,然後才分配給ontouchevent()進行處理。 如果ontouch()對觸控事件進行了處理,並且返回true;那麼,該觸控事件就不會分配在分配給ontouchevent()進行處理了。只有當ontouch()沒有處理,或者處理了但返回false時,才會分配給ontouchevent()進行處理。

Android 觸控事件的機制和原理

一 觸控事件型別 有action down action move action up 三種型別。二 事件傳遞的三個階段 1.分發 dispatchtouchevent,返回true 表示事件被當前檢視消費掉,不在繼續分發事件 返回 super 表示繼續分發該事件,如果當前檢視是 viewgroup...

android觸控語音事件

android中的各種事件是由各種不同的 來完成,比如按鍵事件是由onclicklistener實現監聽,觸控是由ontouchlistener實現監聽的。首先設定監聽,然後傳入要監聽的事件 public class touch913mainactivity extends activity tv....

關於android 的觸控事件

android 觸控motionevent 事件 motionevent 事件物件 一般情況下是在view 的ontouchevent 方法中處理motionevent 事件物件的 1 首先需要獲事件的型別 可以通過getaction android2.2之後加入多點觸控支援後 使用getactio...