android touchEvent事件学习

时间:2023-03-09 19:55:39
android touchEvent事件学习

学习网址:http://www.apkbus.com/forum.php?mod=viewthread&tid=44296

1:Android Touch事件传递机制解析
android系统中的每个View的子类都具有下面三个和TouchEvent处理密切相关的方法:
1)public boolean dispatchTouchEvent(MotionEvent ev)   分发TouchEvent
2)public boolean onInterceptTouchEvent(MotionEvent ev)  拦截TouchEvent
3)public boolean onTouchEvent(MotionEvent ev) 处理TouchEvent

2、传递流程

(1) 事件从Activity.dispatchTouchEvent()开始传递,只要没有被停止或拦截,从最上层的View(ViewGroup)开始一直往下(子View)传递。子View可以通过onTouchEvent()对事件进行处理。

(2) 事件由父View(ViewGroup)传递给子View,ViewGroup可以通过onInterceptTouchEvent()对事件做拦截,停止其往下传递。

(3) 如果事件从上往下传递过程中一直没有被停止,且最底层子View没有消费事件,事件会反向往上传递,这时父View(ViewGroup)可以进行消费,如果还是没有被消费的话,最后会到Activity的onTouchEvent()函数。

(4) 如果View没有对ACTION_DOWN进行消费,之后的其他事件不会传递过来。

(5) OnTouchListener优先于onTouchEvent()对事件进行消费。

上面的消费即表示相应函数返回值为true。

下面看个实例:定义了2种状态

状态1:由center处理Touch事件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<dk.touch.MyLayout
android:id="@+id/out"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#ff345600"
>
<dk.touch.MyLayout
android:id="@+id/middle"
android:layout_width="200dp"
android:layout_height="200dp"
android:gravity="center"
android:background="#ff885678"
>
<dk.touch.MyLayout
android:id="@+id/center"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#ff345678"
android:focusable="true"
android:focusableInTouchMode="true"
android:clickable="true"
>
</dk.touch.MyLayout>
</dk.touch.MyLayout>
</dk.touch.MyLayout>
</LinearLayout>

处理机制效果图:

android touchEvent事件学习

状态2:都不处理事件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<dk.touch.MyLayout
android:id="@+id/out"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#ff345600"
>
<dk.touch.MyLayout
android:id="@+id/middle"
android:layout_width="200dp"
android:layout_height="200dp"
android:gravity="center"
android:background="#ff885678"
>
<dk.touch.MyLayout
android:id="@+id/center"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#ff345678"
>
</dk.touch.MyLayout>
</dk.touch.MyLayout>
</dk.touch.MyLayout>
</LinearLayout>

处理机制效果图:

android touchEvent事件学习

继续学习中