首先從字面意思理解兩個詞
ontouchevent:觸發觸摸事件
onintercepttouchevent:觸發攔截觸摸事件
通過查看源代碼及類繼承關系
onintercepttouchevent:是定義于viewgroup里面的一個方法,此事件是用于攔截觸摸事件的,viewgroup(繼承自view),一個view的group,也就是我們的一個布局如linerlayout,各個布局類都繼承自viewgroup;
ontouchevent:是定義于view中的一個方法,處理傳遞到view的手勢觸摸事件。手勢事件類型包括action_down,action_move,action_up,action_cancel等事件;
其中viewgroup里的onintercepttouchevent默認返回值是false,這樣touch事件會傳遞到view控件,viewgroup里的ontouchevent默認返回值是false;
view里的ontouchevent默認返回值是true,當我們手指點擊屏幕時候,先調用action_down事件,當ontouchevent里返回值是true的時候,ontouch會繼續調用action_up事件,如果ontouchevent里返回值是false,那么ontouchevent只會調用action_down而不調用action_up。
1、新建兩個類llayout , lview 如下
public class llayout extends framelayout {
// viewgroup
@override
public boolean onintercepttouchevent(motionevent ev) {
log.i("ltag", "llayout onintercepttouchevent");
log.i("ltag", "llayout onintercepttouchevent default return" + super.onintercepttouchevent(ev));
return super.onintercepttouchevent(ev);
}
// view
@override
public boolean ontouchevent(motionevent event) {
log.i("ltag", "llayout ontouchevent");
log.i("ltag", "llayout ontouchevent default return" + super.ontouchevent(event));
return super.ontouchevent(event);
}
}
public class lview extends button {
// textview <-- view
@override
public boolean ontouchevent(motionevent event) {
log.i("ltag", "ontouchevent");
log.i("ltag", "ontouchevent default return" + super.ontouchevent(event));
return super.ontouchevent(event);
}
}
2、修改布局文件為如下布局
<com.touchpro.llayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.touchpro.lview
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/app_name" />
</com.touchpro.llayout>
(1)先點擊界面中的按鈕
(2)再點擊界面中的其它區域
結論:llayout 中 onintercepttouchevent 默認返回值為false,ontouchevent 默認返回值為false,所以只調用了action_down事件;
lview中 ontouchevent 默認返回值為true;調用了action_down,action_up 兩個事件;
(3)修改llayout中onintercepttouchevent返回值為true,再次運行代碼:
結論:llayout中onintercepttouchevent返回了true,對觸摸事件進行了攔截,所以沒有將事件傳遞給view,而直接執行了llayout中的ontouchevent事件;
(4)把llayout中onintercepttouchevent返回值改為false,再把lview中的ontouchevent改為返回false:
結論:由于將lview中ontouchevent返回值修改為false,因此只執行了action_down,然后就到llayout中執行ontouchevent事件了;
viewgroup里的onintercepttouchevent默認值是false這樣才能把事件傳給view里的ontouchevent.
viewgroup里的ontouchevent默認值是false。
view里的ontouchevent返回默認值是true.這樣才能執行多次touch事件。